无法让WinJS.xhr正确检索XML文件

时间:2014-03-23 05:37:27

标签: 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");

        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 });
        }
    });
}

如果我将BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray });放在WinJS.xhr代码块之外,它会成功地向数组BasketballItems添加一个元素,但是如果我把它放在那个大块代码中,它就不会不起作用。我正在调用这样的函数:HelloFeed("http://allball.blogs.nba.com/feed/");

我做错了什么?

1 个答案:

答案 0 :(得分:2)

在异步操作完成并运行回调之前尝试使用异步操作后处理的数据似乎是一个经典错误。无论代码需要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)
}

根据范围的不同,您可能不需要像我那样传递BasketballItems。看起来您可以隐式访问它,但我不建议使用这种非封装变量。

为了澄清我的意思,你也可以在回调中做到这一点:

function myOtherCode() {
  console.log(BasketballItems);
}

当然,您也可以不使用函数,而只是将所有代码转储到那里,但最好还是尝试更多地破解代码。