我正在使用google feed api进行实验。基本上我想要一个我的供稿列表以及供稿条目的一些信息,以便处理谷歌阅读器上通常不可用的历史供稿。我对google feed api的一个行为感到困惑,我在下面的代码中记录为评论。因为我是js的新手,所以我确定我没有得到任何东西。
这是我的问题代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" charset="UTF-8" >
google.load("feeds", "1");
/* Here I define the list of my feeds */
var feeds=['MYFEED1', 'MYFEED2', 'AND SO ON'];
function initialize() {
for (var j=0;j<feeds.length;j++) {
var feed = new google.feeds.Feed(feeds[j]);
feed.includeHistoricalEntries();
feed.setNumEntries(100);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("out");
var furl = result.feed.feedUrl;
var flink = result.feed.link;
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
/* HERE IS WHERE I DON'T GET IT.
feeds[j] always just shows the last feed in the array.
But furl always shows the correct feedUrl
Though if I uncomment alert("NEXT") few lines below
thus giving a short pause, feeds[j] correctly
shows the same url as feedUrl. Why? */
div.appendChild(document.createTextNode(feeds[j]+" "
+furl+" "+flink+" "+ entry.link + " " + entry.title));
container.appendChild(div);
}
}
});
//alert("NEXT");
}
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body><div id="out" ></div>
</body>
</html>
另外我想知道是否有办法通过查询mysql数据库来设置feeds数组的值。
答案 0 :(得分:1)
在我看来,feed.load()是一个ajax调用,并且您正在传递一个回调函数,以便在从请求返回时执行。因为ajax是异步的,所以外部for循环继续执行,因此你总是看到数组中的最后一个feed。
我相信在这种情况下,闭包应该会帮助你。
考虑将整个块放在外部for循环中,并使用闭包。 像这样:
function initialize() {
for (var j = 0; j < feeds.length; j++) {
(function(val) { //closure begin
var j = val;
var feed = new google.feeds.Feed(feeds[j]);
feed.includeHistoricalEntries();
feed.setNumEntries(100);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("out");
var furl = result.feed.feedUrl;
var flink = result.feed.link;
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
/* HERE IS WHERE I DON'T GET IT.
feeds[j] always just shows the last feed in the array.
But furl always shows the correct feedUrl
Though if I uncomment alert("NEXT") few lines below
thus giving a short pause, feeds[j] correctly
shows the same url as feedUrl. Why? */
div.appendChild(document.createTextNode(feeds[j] + " " + furl + " " + flink + " " + entry.link + " " + entry.title));
container.appendChild(div);
}
}
}
})(j); //Closure end
});
//alert("NEXT");
}