1

我开始使用 Javascript 开发 Win8 应用程序。我是 javascript 新手,因此我对这门语言不太熟悉。我正在尝试在我的代码中解析一个 json 响应并将其存储在一个数组中。现在我希望数组是具有特定属性的对象,我试图在解析步骤中设置这些属性。但是,该数组似乎没有在 WinJS.xhr 部分中更新。为了更清楚,REF 1(下面代码中的注释)控制台输出工作正常,但是 REF 2(下面代码中的注释)控制台输出抛出如下错误:

JavaScript 运行时错误:无法获取未定义或空引用的属性“名称”

var sampleArr = new Array();

WinJS.xhr({ url: "http://some-api-with-json-response" }).then(
       function (response) {
           var name= JSON.parse(response.responseText);
           sampleArr[0] = { Name: name.title };
           console.log("First chance:" + sampleArr[0].Name); //REF 1
           item_number++;
           };

console.log("Second chance:" + sampleArr[0].Name); //REF 2

谁能告诉我,我哪里错了?

谢谢 :)

4

2 回答 2

2

.then(callback),callback请求成功时执行该函数。

REF 2在函数之前运行的代码callback,当时sampleArr[0]undefined.

于 2012-10-12T06:14:18.693 回答
2

问题是 XHR 调用是在后台执行的,而在这种情况下,JavaScript 运行时会继续执行下一条语句——即REF2. 因此,您试图在请求本身完成之前读取请求的结果。

解决方案是将访问结果的代码放在传递给该then方法的另一个调用的函数中,如下所示:

var sampleArr = new Array();

WinJS.xhr({ url: "http://some-api-with-json-response" }).then(
       function (response) {
           var name = JSON.parse(response.responseText);
           sampleArr[0] = { Name: name.title };
           console.log("First chance:" + sampleArr[0].Name); //REF 1
           item_number++;

       }).then(function () {
           console.log("Second chance:" + sampleArr[0].Name); //REF 2
       });

包含REF2的函数在包含的函数REF1完成之前不会执行,并且在 XHR 请求完成之前不会执行该函数。

于 2012-10-12T21:29:48.740 回答