0

私は Ajax の完全な初心者なので、これが完全にばかげたコードである場合はご容赦ください。

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);
    });
  }

ここでの目標は、指定された値で controller.php を実行し、返された情報を使用して各呼び出しに「オフセット」をプラグインすることです。動作しますが、0 から 10 まで瞬時に実行され、Web サーバーは後続の呼び出しを拒否します。

私の目標は、最後の操作が完了するまでphpを再度呼び出さないようにすることです。

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 に答える