Javascript 无法获取WinJS.xhr以正确检索XML文件
以下是我所拥有的:Javascript 无法获取WinJS.xhr以正确检索XML文件,javascript,windows-8,microsoft-metro,Javascript,Windows 8,Microsoft Metro,以下是我所拥有的: function HelloFeed(WPFeedUrl) { var title, articles; WinJS.xhr({ url: WPFeedUrl }).then(function (rss) { title = rss.responseXML.querySelector("title").textContent; var items = rss.responseXML.querySelectorAll("item"
function HelloFeed(WPFeedUrl) {
var title, articles;
WinJS.xhr({ url: WPFeedUrl }).then(function (rss) {
title = rss.responseXML.querySelector("title").textContent;
var items = rss.responseXML.querySelectorAll("item");
for (var n = 0; n < items.length; n++) {
var article = {};
article.title = items[n].querySelector("title").textContent;
var thumbs = items[n].querySelectorAll("content");
article.content = items[n].querySelector("encoded").textContent;
if (thumbs.length > 1) {
article.thumbnail = thumbs[thumbs.length - 1].attributes.getNamedItem("url").textContent;
}
else {
var firstindex = article.content.indexOf("<img");
if (firstindex !== -1) {
var secondindex = article.content.indexOf("src=", firstindex) + 5;
var thirdindex = article.content.indexOf("\"", secondindex);
article.thumbnail = article.content.slice(secondindex, thirdindex);
}
}
BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray });
}
});
}
函数HelloFeed(WPFeedUrl){
标题、文章;
xhr({url:WPFeedUrl})。然后(函数(rss){
title=rss.responseXML.querySelector(“title”).textContent;
var items=rss.responseXML.queryselectoral(“项”);
对于(变量n=0;n1){
article.thumb=thumbs[thumbs.length-1].attributes.getNamedItem(“url”).textContent;
}
否则{
var firstindex=article.content.indexOf(“
如果我放置BasketballItems.push({group:BasketballGroups[0],标题:“hello”,内容:“h”,背景图像:lightGray})
在WinJS.xhr
代码块之外,它成功地将一个元素添加到数组BasketballItems
,但是如果我将它放在那大块代码中,它就不起作用了。我调用的函数如下:HelloFeed(“http://allball.blogs.nba.com/feed/”;
我做错了什么?在异步操作完成并运行回调之前,尝试使用异步操作后处理的数据似乎是一个典型的错误。任何需要BasketballItems
的代码都应作为该代码块的一部分进行调用。例如:
BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray });
myOtherCode(BasketballItems);
然后将需要了解这些项的代码放入该函数中。这只是另一个回调
function myOtherCode(items) {
console.log(items); // <--- code in here knows about the push, since it occurs in the callback chain after the asynchronous operation (WinJS.xhr)
}
当然,您也可以不使用函数而直接将所有代码转储到此处,但最好尝试将代码进一步分解。我对您的解决方案和答案感到有点困惑,但是,如果这能让问题更清楚的话,下面是我拥有的整个data.js文件:
function myOtherCode() {
console.log(BasketballItems);
}