0

I am a complete noob to Ajax so please forgive me if this is a completely asinine piece of code:

for (var i=0; i<11; i++) {
    jQuery('#position').html(i);
    var offset = jQuery('#offset').html();
    var postcall = 'controller.php?url='+encodeURIComponent(scrapurl)+'&scrape_absolute='+absoluteep+'&scrape_season='+season+'&scrape_show='+showslug+'&scrape_defimg='+encodeURIComponent(defaultimg)+'&offset='+offset;
    jQuery.post(postcall,function(data){
    jQuery('#offset').html(data);
    });
  }

The goal here is to execute controller.php with the given values and plug 'offset' back into each call using the returned info. It works but it runs from 0 to 10 instantly and my webserver rejects the subsequent calls.

My goal is to make sure it doesn't call the php again until the last operation has completed.

4

2 回答 2

2

关键是在回调函数中进行下一次 AJAX 调用。这样,您的下一篇文章在第一次完成之前不会出现。在您的代码中,因为.post()是非阻塞(异步),它会立即继续循环,递增i/#position并触发下一个.post()

为了解决这个问题,将你封装.post()在一个包装函数中。有一个计数器来跟踪它被调用了多少次。从 的回调中调用该函数.post(),您最终会得到一个递归函数,该函数将按顺序执行调用:

var position=0;

function doNextAJAXPost() {
    if(position < 11) {
        jQuery('#position').html(position);
        position++;
        var offset = jQuery('#offset').html();

        jQuery.post('controller.php?url='+encodeURIComponent(scrapurl)+'&scrape_absolute='+absoluteep+'&scrape_season='+season+'&scrape_show='+showslug+'&scrape_defimg='+encodeURIComponent(defaultimg)+'&offset='+offset, function(data){
            jQuery('#offset').html(data);
            doNextAJAXPost();
        });
    }
}

doNextAJAXPost();
于 2013-03-04T18:07:16.337 回答
0

使用自执行递归函数

(function callself(i) {
  jQuery('#position').html(i);
  var offset = jQuery('#offset').html();
  var postcall = 'controller.php?url='+encodeURIComponent(scrapurl)+'&scrape_absolute='+absoluteep+'&scrape_season='+season+'&scrape_show='+showslug+'&scrape_defimg='+encodeURIComponent(defaultimg)+'&offset='+offset;
  jQuery.post(postcall,function(data){
    jQuery('#offset').html(data);
    i++;
    if ( i < 11 ) callself(i);
  });
})(0)
于 2013-03-04T18:11:15.937 回答