[英]making synchronous request in Ajax, for jQuery 1.8
我阅读了很多人提出的大多数问题,但正如jQuery 1.8.X async文档中所建议的那样:不建议使用false。
用例:我想获取一个位置主题的所有推文(使用Twitter搜索API),我可以使用地址解析和q参数获取该信息。
但我需要获取所有页面,因为我们知道您可以从twitter api的建议中获得15 * 100的api结果。
CODE:可以在这里找到。 http://pastebin.com/rgVDQFve
问题是tweetsPerPage未定义,因为getTweets返回的对象的状态为1,但其状态应该为4。
我正在使用jQuery 1.8.2,但尝试对其进行更改但没有任何效果。
任何人都可以提出一些建议。
function main() {
for(hindex=0; hindex<HASHTAGS.length; hindex++) {
for (cindex=0; cindex<COORDINATES.length;cindex++) {
for (pindex=0; pindex<NUMBER_OF_PAGES; pindex++) {
getTweets(HASHTAGS[hindex], COORDINATES[cindex][1], COORDINATES[cindex][2], pindex+1, function(tweets) {
TWEETS = TWEETS.concat(tweets); /*basically I am getting all the tweets in this, I just need a way by which after executing all the getTweets along with their success functions and the callback I get the control to myself which will help me in using TWEETS*/
});
}
}
}
}
function getTweets(hashtag, latitude, longitude, pageIndex, callback) {
$.ajax({
url: 'http://search.twitter.com/search.json',
cache: false,
dataType: 'jsonp',
data: {
q: hashtag,
geocode: latitude + "," + longitude + "," + RADIUS,
page: pageIndex,
rpp: RESULTS_PER_PAGE,
result_type: RESULT_TYPE
},
success: function (data) {
var results = data.results;
var tweets = [];
$(results).each(function(index, tweetJSON) {
var tweet = {
created_at: 'Dhruven' + " " + pageIndex + " " + (index+1)
};
var tweetObj = JSON.stringify(tweet);
tweets.push(tweetObj);
});
callback(tweets);
}
});
}
如评论中所述,jsonp请求不支持同步请求。
但是带有回调的异步请求似乎可以正常工作,请参见小提琴:
http://jsfiddle.net/andreortigao/hAevy/
码:
function getTweets(hashtag, latitude, longitude, pageIndex, callback) {
$.ajax({
url: 'http://search.twitter.com/search.json',
type:'GET',
dataType: 'jsonp',
data: {
q: hashtag,
geocode: latitude + "," + longitude + "," + '10mi',
page: pageIndex,
rpp: 10,
result_type: 'recent'
},
success: function (data, status, xmlHttp) {
var results = data.results;
var tweets = [];
$(results).each(function(index, tweetJSON) {
var tweet = {
created_at: 'Dhruven' + " " + pageIndex + " " + (index+1)
};
var tweetObj = JSON.stringify(tweet);
tweets.push(tweetObj);
});
callback(data.results);
}
});
}
呼叫:
getTweets("#facebook", 42.3580555555556, -71.0602777777778, 2, function(tweets){
$("#log").text(JSON.stringify(tweets)); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.