我希望同时运行多个不同的JSON请求,然后只有在完成或返回错误消息后才执行函数(404等)。这是我到目前为止所做的,但函数finished
不记得任何一个请求中的变量。有什么想法吗?
function socialPosting(a_date,a_title,a_source,a_thumbnail,a_url) {
socialPosts[socialPosts.length] = {date: a_date, title: a_title, source: a_source, thumbnail: a_thumbnail, url: a_url};
//console.log(socialPosts[amount]);
//console.log(amount);
}
function finished(source) {
if (source == "Twitter") {
var Twitter = "True";
}
if (source == "YouTube") {
var YouTube = "True";
}
console.log(source); //diagnostics
console.log(Twitter); //diagnostics
console.log(YouTube); //diagnostics
if (Twitter == "True" && YouTube == "True") {
console.log(socialPosts[0]); //Should return after both requests are complete
}
}
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
socialPosting(Date.parse(data.data.items[i].uploaded),data.data.items[i].title,"YouTube",data.data.items[i].thumbnail.hqDefault,'http://www.youtube.com/watch?v=' + data.data.items[i].id); //Add values of YouTube video to array
}
finished("YouTube");
});
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/twitter.json?count=5&include_rts=1&callback=?", function(data) {
var amount = socialPosts.length;
for(var i=0; i<data.length; i++) {
socialPosting(Date.parse(data[i].created_at),data[i].text,"Twitter"); //Add values of YouTube video to array
}
finished("Twitter");
});
答案 0 :(得分:1)
var Twitter = false;
var YouTube = false;
function finished(source) {
if (source == "Twitter") {
Twitter = true;
}
if (source == "YouTube") {
YouTube = true;
}
console.log(source);
console.log(Twitter);
console.log(YouTube);
if (Twitter && YouTube) {
console.log(socialPosts[0]);
}
}
还通过
向json-request添加错误处理程序
$.getJSON(...).fail(function () {console.log('error');});