gpt4 book ai didi

javascript - Google Feed API 行为

转载 作者:行者123 更新时间:2023-11-28 02:36:16 24 4
gpt4 key购买 nike

我正在使用 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 数组的值。

最佳答案

在我看来 feed.load() 是一个 ajax 调用,并且您正在传递一个回调函数以在从请求返回时执行。由于 ajax 是异步的,因此外部 for 循环会继续执行,因此您始终会看到数组中的最后一个提要。

我相信在这种情况下闭包应该对您有所帮助。

考虑将整个 block 放置在单独函数的外部 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");
}​

关于javascript - Google Feed API 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13443230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com