近两天来,我一直在尝试获取YUI JSON实用程序:在解析过程中添加新的对象成员无法正常工作。

这对我来说很难,因为我是编码新手。在尝试将不同的JS文件,引用和脚本放入项目后,我使用了Configurator脚本。

我尝试在Explorer和Firefox中运行代码;但是,结果表将不会显示。

代码运行是因为页面显示错误消息:“错误获取库存数据”,这是页面代码中的try / catch错误消息。

文本编辑器错误控制台中的错误消息可能与未显示的数据有关吗?

文本编辑器错误控制台显示错误(第76行,第12列)-未知属性:错误控制台中的单元格间距



Mozilla Firefox错误控制台也显示错误:

 Error: ReferenceError: YUI is not defined
    Source File: http://localhost:53753/currency.html
    Line: 87


Firefox识别的第87行的代码行是:

<tr><td colspan="4">Click <em>Get Data</em></td></tr>




YUI库中的示例代码位于:http://developer.yahoo.com/yui/examples/json/json_convert_values.html

这是我完整的代码:

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
        <title>Example: Adding New Object Members During Parsing</title>

    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="css/grids-min.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="images/favicon.png">

</head>

<body>
<!--
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-->

    <div id="doc">
        <div id="hd">

        <h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1>

    </div>
        </div>
    <div id="demo">
        <p>Choose a currency, then get the data</p>

        <select>
        <option value="ARS">Argentine Peso</option>
        <option value="AUD">Australian Dollar</option>
        <option value="BRL">Brazilian Real</option>
        <option value="GBP">British Pound</option>
        <option value="CAD">Canadian Dollar</option>
        <option value="CNY">Chinese Yuan</option>
        <option value="COP">Colombian Peso</option>
        <option value="HRK">Croatian Kuna</option>
        <option value="CZK">Czech Koruna</option>
        <option value="DKK">Danish Krone</option>
        <option value="EEK">Estonian Kroon</option>
        <option value="EUR">Euro</option>
        <option value="HKD">Hong Kong Dollar</option>
        <option value="HUF">Hungarian Forint</option>
        <option value="ISK">Iceland Krona</option>
        <option value="INR">Indian Rupee</option>
        <option value="JPY">Japanese Yen</option>
        <option value="KRW">Korean Won</option>
        <option value="LVL">Latvian Lat</option>
        <option value="LTL">Lithuanian Lita</option>
        <option value="MYR">Malaysian Ringgit</option>
        <option value="MXN">Mexican Peso</option>
        <option value="NZD">New Zealand Dollar</option>
        <option value="NOK">Norwegian Krone</option>
        <option value="PHP">Philippine Peso</option>
        <option value="PLN">Polish Zloty</option>
        <option value="RUB">Russian Rouble</option>
        <option value="SGD">Singapore Dollar</option>
        <option value="SKK">Slovak Koruna</option>
        <option value="ZAR">South African Rand</option>
        <option value="LKR">Sri Lanka Rupee</option>
        <option value="SEK">Swedish Krona</option>
        <option value="TRY">Turkey Lira</option>
        <option value="USD" selected="selected">U.S. Dollar</option>
        <option value="CHF">Swiss Franc</option>
        <option value="TWD">Taiwan Dollar</option>
        <option value="THB">Thai Baht</option>
    </select>

        <input type="button" id="demo_go" value="Get Data">

    <table cellspacing="0">
        <caption>Inventory</caption>
            <thead>
        <tr>
            <th>SKU</th>
            <th>Item</th>
            <th>Price (USD)</th>
            <th>Price (<span>USD</span>)</th>
        </tr>
            </thead>
    <tbody>
        <tr><td colspan="4">Click <em>Get Data</em></td></tr>
     </tbody>
   </table>
 </div>

<!-- JS -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?3.8.1/build/yui-base/yui-base-min.js&3.8.1/build/json-parse/json-parse-min.js&3.8.1/build/json-stringify/json-stringify-min.js"></script>

<script>
    YUI().use("node", "io", "json-parse",function (Y) {

// Safari 4.0.3's native JSON does not support adding members during parse,
// so use JavaScript implementation for consistency
    Y.JSON.useNativeParse = false;

var example = {
    rates : {"USD":1,"EUR":0.6661,"GBP":0.5207,"AUD":1.1225,"BRL":1.609,"NZD":1.4198,"CAD":1.0667,"CHF":1.0792,"CNY":6.8587 ,"DKK":4.9702,"HKD":7.8064,"INR":42.0168,"JPY":109.8901,"KRW":1000,"LKR":107.5269,"MXN":10.1317,"MYR" :3.3167,"NOK":5.3277,"SEK":6.2617,"SGD":1.4073,"THB":33.7838,"TWD":31.1526,"VEF":2.1445,"ZAR":7.6923 ,"BGN":1.3028,"CZK":16.0514,"EEK":10.4275,"HUF":158.7302,"LTL":2.2999,"LVL":0.4692,"PLN":2.1758,"RON" :2.3804,"SKK":20.2429,"ISK":4.8008,"HRK":81.3008,"RUB":24.3309,"TRY":1.1811,"PHP":44.2478,"COP":2000 ,"ARS":3.1289},

    currency : 'USD',

    convert : function (k,v) {
        // 'this' will refer to the object containing the key:value pair,
        // so this step will add a new object member while leaving the original
        // intact (but formatted to two decimal places).  If the original
        // is not needed, just return the converted value.

        if (k === 'Price') {
            var x = Math.round(v * example.rates[example.currency] * 100) / 100;
                this.convertedPrice = x.toFixed(2); // added to item
                    return v.toFixed(2); // assigned to item.Price
        }
        return v;
    },

    updateTable : function (inventory) {
        // Update the column header
        Y.one('#demo table th span').set('innerHTML',example.currency);

        var tbody = Y.one('#demo table tbody'),
            html  = ['<table><tbody>'],
            rowTemplate = '<tr><td>{SKU}</td><td>{Item}</td><td>{Price}</td><td>{convertedPrice}</td></tr>',
            i, len;

        if (inventory) {
            for (i = 0, len = inventory.length; i < len; ++i) {
                html.push(Y.Lang.sub(rowTemplate, inventory[i]));
            }
        } else {
            html.push('<tr><td colspan="4">No Inventory data</td></tr>');
        }

        html.push('</tbody></table>');

        tbody.replace(Y.Node.create(html.join('')).one('tbody'));
    }
};

Y.one('#demo_go').on('click', function (e) {
    // Disable the button temporarily
    this.set('disabled',true);

    // Store the requested currency
    var sel = Y.one("#demo select");
    example.currency = sel.get("options").item(sel.get("selectedIndex")).get("value");

    Y.io('js/json-convert-values-response.json',{
        timeout : 3000,
        on : {
            success : function (xid, res) {
                var inventory;
                try {
                    inventory = Y.JSON.parse(res.responseText,example.convert);

                    example.updateTable(inventory);
                }
                catch(e) {
                    alert("Error getting inventory data");
                }
                finally {
                    Y.one('#demo_go').set('disabled',false);
                }
            },
            failure : function () {
                alert("Error getting inventory data");
            }
        }
    });
});

// Expose example objects for inspection
YUI.example = example;
});
</script>
    </body>
        </html>


更新-显然,这些JSON示例在jsfiddle上不起作用,因为它们正在使用XHR来获取JSON数据。这些数据在他们的服务器上不存在,因此将归档。因此,请忽略该字段

这是我的问题的JS提琴,任何人都可以帮助我解决这个问题吗?

解析期间添加新的对象成员:http://jsfiddle.net/DanyB/3ntvw/

谢谢任何有心人来看看。

最佳答案

正如Bergi在上面的评论中所说,脚本似乎没有足够早地加载或执行。

一种可能的解决方案...

为确保正确,您应该在HTML的头部声明YUI脚本标签。首先尝试看看是否可以解决您的问题。然而...

...

等待直到准备就绪

您也应该将其他代码放在开头,但是要指定它,以便仅在整个文档加载后才加载。

最简单的方法是:

window.onload = function () { // what to do when window has loaded
    YUI().use("node", "io", "json-parse",function (Y) {

    // ... the code in your callback function, as provided above ...

    }); // end callback -- UPDATED
}; // end window onload function


YUI拥有自己的处理代码的方式,该方式应在文档准备好时...

YAHOO.util.Event.onDOMReady


但是由于您的问题是未定义YUI,因此我不确定这是否有帮助。

...

检查和安全模式?

更复杂的模式可能涉及设置间歇检查以查看是否定义了YUI,然后取消检查并执行所需的代码。那将使用称为setInterval()的方法,如下所示:

var checkYUI = setInterval(function() { // create a function to be executed within the interval and assign the interval to a global variable
    if (YUI) { // check the global variable `YUI` exists
        clearInterval(checkYUI); // cancel the interval check
        YUI().use("node", "io", "json-parse",function (Y) { // now we know `YUI` exists call its `use()` method
            // ... the code in your callback function, as provided above ...
        }
    }
}, 100); // checks every 100 ms


您可以通过例如检查YUI是否是对象,是否具有use()方法等来使检查更加复杂。但是希望这足以说明它如何工作。

我不确定您在先前的试验中做了什么使它们成功,而这次试验失败了,但是值得研究一下它们是否已经到位。

关于javascript - YUI JSON-如何在解析期间添加新的对象成员?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15203864/

10-13 00:23