看一下下面的代码。问题很简单,如果方法findUserInfo ajax代码返回错误,我该如何中断此for循环。简而言之,我怎么才能在我想要的时候从这个for循环中解脱出来呢?是因为ajax调用是异步的吗?
jQuery.each(d, function() {
findUserInfo(this);
});
function findUserInfo(userID){
var req = $.ajax({
url: "http://twitter.com/users/show.json?suppress_response_codes&id=xx!5@x!!x",
dataType : "jsonp"
});
req.success(function(msg) {
console.log('Yes! Success!');
});
req.error(function(msg) {
console.log('Error');
});
} 发布于 2012-04-20 01:29:34
是的,jQuery.ajax是异步的,所以你需要使用类似这样的东西:
function findUserInfos(datas){
var userID=datas.shift(); //remove and return the first element
var req = $.ajax({
url: "http://twitter.com/users/show.json?suppress_response_codes&id=xx!5@x!!x",
dataType : "jsonp"
});
req.success(function(msg) {
console.log('Yes! Success!');
findUserInfos(datas)
});
req.error(function(msg) {
console.log('Error');
});
}
findUserInfos(d);一旦出现错误,它就会崩溃,因为我们只有在成功中才能继续。
发布于 2012-04-20 01:36:33
设置async:false是一个糟糕的想法。它会导致浏览器在进行ajax调用时挂起。Frame.js的设计目的是解决这样的问题:
jQuery.each(d, function() {
findUserInfo(this);
});
Frame.useTimeout = false; // turn off Frame's error recovery
function findUserInfo(userID){
Frame(function(next){
var req = $.ajax({
url: "http://twitter.com/users/show.json?suppress_response_codes&id=xx!5@x!!x",
dataType : "jsonp"
});
req.success(function(msg) {
console.log('Yes! Success!');
next();
});
req.error(function(msg) {
console.log('Error');
// don't call next and Frame will stop
});
});
}
Frame.init();发布于 2012-04-20 01:30:50
要中断循环,请返回false
如果在错误处理程序中抛出错误:
throw 'Error: ' + userID;然后,您可以编写
jQuery.each(d, function() {
try {
findUserInfo(this);
} catch(err) {
return false;
}
});编辑:正如其他人所说,最好从成功处理程序返回true,从错误处理程序返回false,然后在循环内调用return findUserInfo(this);。当然,如果同步进行ajax调用,则可能会冻结浏览器。
https://stackoverflow.com/questions/10233374
复制相似问题