我正在为Windows 8制作我的第一个WinJS应用程序,我只是想替换2网格模板中给出的基本代码,我收到了这个错误:
Unable to get property 'forEach' of undefined or null reference
我的代码:
getData().forEach(function (item) {
list.push(item);
});
初始功能:
function getData() {
// JSON request
WinJS.xhr({
type: "GET",
url: "http://mytld.com/mobile/pagethatreturnsjsondata.php"
}).then(
function (response) {
OnSuccessCall(response);
},
function (error) {
var err = error;
console.log("Error : " + err.message);
},
function (progress) { }
);
}
以下是从返回JSON数据的php webservice获取数据:
function OnSuccessCall(response) {
var itemContent = "<p>Item Content</p>";
var itemDescription = "Item Description";
var groupDescription = "Group Description";
// These three strings encode placeholder images. You will want to set the
// backgroundImage property in your real data to be URLs to images.
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
var lightGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY7h4+cp/AAhpA3h+ANDKAAAAAElFTkSuQmCC";
var mediumGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
// Each of these sample groups must have a unique key to be displayed separately.
var sampleGroups = [
{ key: "group1", title: "prayers", subtitle: "submitted prayers", backgroundImage: darkGray, description: groupDescription }
];
var x = response.responseText.length;
var json = JSON.parse(response.responseText);
var sampleItems = [];
for (var i = 0; i < json.length - 1; i++) {
sampleItems.push({
group: sampleGroups[0],
title: json[i].text,
subtitle: "Item Subtitle: 1",
description: itemDescription,
content: itemContent,
backgroundImage: lightGray
});
}
return sampleItems;
}
我能够在sampleItems中看到数据:
我显然做错了,因为当我将对象结果与原始示例数据的结果进行比较时,它们实际上是相同的。
感谢任何帮助。
答案 0 :(得分:3)
您的getData()
函数没有return
语句,因此返回undefined
。你不能在forEach
上undefined
。
从更大的角度来看:您的getData()
使用xhr
,因此它实际上并不返回结果,而是异步获取数据。因此,您不能forEach
返回值,因为结果尚不存在。您必须等待承诺完成,然后您可以在承诺结果上致电forEach
。
function getData() {
// add "return" here so the function returns a Promise
return WinJS.xhr({
type: "GET",
url: "http://mytld.com/mobile/pagethatreturnsjsondata.php"
}).then(
function (response) {
// add "return" here to specify the promise's completed value
return OnSuccessCall(response);
},
function (error) {
var err = error;
console.log("Error : " + err.message);
},
function (progress) { }
);
}
现在getData()
返回了一些内容(一个Promise),你可以安排在promise完成时进行工作。
getData().then(function(results) { results.forEach(...) });