无法获取WinJS.以正确检索XML文件

Unable to get WinJS.xhr to properly retrieve XML file

本文关键字:检索 XML 文件 获取 WinJS      更新时间:2023-09-26

我有:

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/");

我做错了什么?

这似乎是在异步操作完成之前尝试使用异步操作后处理的数据并运行回调的典型错误。任何需要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);
}

当然,您也可以不使用函数,而是直接将所有代码转储在那里,但最好尝试将代码更分解。