3

我在循环中有一个 jQuery POST 函数(多个 post 调用)。
出于某种原因,jQuery 正在发布,但在循环结束并立即解析所有结果之前不会返回所有数据。

FOREACH arg_value IN args
{
console.log('Do stuff');

    $.post('https://blah.com/xml.php',
           {arg: arg_value},
           function(xml) {
                $(xml).find('tag').each(function() {
                        console.log('Do more stuff');
                });
           });
}

这个输出是...

做事
做事
做事
做更多事
做更多事
做更多事

似乎 jQuery 正在缓存结果或直到最后才执行它。

我期待着...

做事
做更多事 做事

更多事 做事

更多事

Is there an option to tell jQuery to pause execution until there is a result from the AJAX? It appears to be running asynchronously as usual, but I don't want that in this case.

4

4 回答 4

3

A AJAX call is asynchronous. This means your callback:

function(xml) {
    $(xml).find('tag').each(function() {
        console.log('Do more stuff');
    });
}

Only gets executed when the server returns a response.

Meanwhile, your for-each loop will keep running, and logging Do stuff.
Unless you're doing crazy stuff in your loop, the loop will be faster than the server response
Like Jan Dvorak mentioned, Even if you do crazy stuff, the AJAX callbacks will wait for the loop to finish, resulting in Do stuff always appearing before any of the AJAX responses.

于 2012-11-30T13:58:41.263 回答
1

Your ajax call is asyncronous, which means that the ajax call is fired off, then the execution flow of further code continues. It does not wait around for the response. When the response is finally received, the callback is executed.

What you could do is to have your ajax calls all stack up in a queue and as each response is received, fire off the next call in the queue. This would achieve your diesired effect, whereby the next ajax call is not sent until the current one is done.

If you have many calls, this would be much slower than firing them all off as soon as they are needed because browsers can easily handle multiple ajax calls at the same time.

于 2012-11-30T14:01:57.293 回答
1

$.post() is async call...will not work in loops the way u want..To get the way u want..here is the solution..

var i=0;
callbackfunc(i) {
console.log('Do stuff');
$.post('https://blah.com/xml.php',
        {arg: args[i]},
        function(xml) {
            $(xml).find('tag').each(function() {
              //something related to xml data  
            });
             console.log('Do more stuff');
              i++;
              if(i<args.length)callbackfunc(i)
           }
        });
}

take care of variables..may create closures here...

于 2012-11-30T14:02:48.107 回答
0

you are asynchronous here, if you want to do that probably the easiest way to achieve this is to use async.js

于 2012-11-30T13:57:46.257 回答