3

@ Phrogz のクイック スクリプトを使用して、次を使用して最後の AJAX リクエストを除くすべてをキャンセルしています。

var fooXHR, fooCounter=0;
$('div').bind( 'click', function(){
  // Do the Right Thing to indicate that we don't care about the request anymore
  if (fooXHR) fooXHR.abort();

  var token = ++fooCounter;
  fooXHR = $.get( ..., function(data){
    // Even aborted XHR may cause the callback to be invoked
    if (token != fooCounter) return;

    // At this point we know that we're using the data from the latest request
  });
});

このスクリプトは非常にうまく機能しますが、ページロードdiv時に一度に 3 秒をロードし、3 つすべての結果をロードすると予想される場合、上記のスクリプトは最後の 1 つだけを表示します (最初の 2 つは上記のスクリプトに基づいて中止されるため)。

囲まれたDOM要素によって上記のスクリプトを制限する正しい方向に私を向けることができますか?

例えば...

<div id="one">1. run ajax on pageload and on click</div>
<div id="two">2. run ajax on pageload and on click</div>
<div id="three">3. run ajax on pageload and on click</div>

3 つの div すべてが、ページロードまたはクリック時に ajax リクエストを返すようにします。そして、クリック時に以前の AJAX リクエストをキャンセルする機能を保持したいと考えています。div#oneしかし、から呼び出された ajax リクエストをキャンセルするためにクリックしたくありませんdiv#two

フォローしますか?

4

1 に答える 1

3

ハッシュを使用して、それぞれの xhr およびカウンター変数を格納するだけですdiv

var requests = {};
$('div').bind( 'click', function(){
  var div = this;

  // init the entry for the div
  if (requests[div] === undefined) {
    requests[div] = {};
    requests[div].counter = 0;
  }

  // abort the old request
  if (requests[div].xhr !== undefined) {
    requests[div].xhr.abort();
  } 

  var token = ++requests[div].counter;
  request[div].xhr = $.get( ..., function(data) {
    // check for correct request
    if (token !== requests[div].counter) return;

    // ...
  });
});
于 2013-05-22T07:19:34.623 に答える