0

trのループでajaxを使用しようとしています。

これが私のコードです:

var i=0;
$("tr").each(function() {
var row = datastring;
console.log("I = " + i);
$.ajax({
    type: 'POST',
    url: 'somelinkgoeshere.com',
    data: row,
    success: function(){console.log("Success")},
    error: function(){console.log("Error")}
});
i++;
});​

期待される結果

したがって、console.logが次の順序でログを返す必要がある順序でイベントを発生させたいと思います。

  1. I = 0
  2. 成功またはエラー
  3. I = 1
  4. 成功またはエラー

実結果

しかし、コードを実行した後、console.logは次の順序でログを返します

  1. I = 0
  2. I = 1
  3. 成功またはエラー
  4. 成功またはエラー

つまり、各ループが完了した後にajax関数が呼び出されるということです。しかし、ajaxリクエストが競合しない限り、関数をループさせたくありません。

さらに説明が必要な場合はお知らせください。

ありがとう。

4

3 に答える 3

2

何度も述べたように、Ajax は非同期です。これは、他の関数とコードを同時に実行できることを意味します。これの利点は、ブラウザーがページ JS の実行を続行する前に、要求が完了するのを待つ必要がないことです。ページに多数の Ajax リクエストがあり、1 つのサーバーが応答するのに 30 秒かかる場合を想像してみてください...

asyncただし、リクエストを同期的に実行したい場合は、フラグをfalse次のように設定できます。

var i = 0;
$("tr").each(function() {
    var row = datastring;
    console.log("I = " + i);
    $.ajax({
        type: 'POST',
        url: 'somelinkgoeshere.com',
        data: row,
        async: false,
        success: function() {
            console.log("Success")
        },
        error: function() {
            console.log("Error")
        }
    });
    i++;
});​

PS手動でインクリメントする必要はありませんi.jQuery.each()はそれを提供できます:

$("tr").each(function(i) {
    var row = datastring;
    console.log("I = " + i);
    $.ajax({
        type: 'POST',
        url: 'somelinkgoeshere.com',
        data: row,
        async: false,
        success: function() {
            console.log("Success")
        },
        error: function() {
            console.log("Error")
        }
    });
});​
于 2012-10-31T14:32:07.230 に答える
1

Use async=false.

Here is a quote from the jQuery documentation:

asyncBoolean Default: true By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/err

or callbacks.

于 2012-10-31T14:23:11.810 に答える
1

asyncfalseに設定する必要があります。

$.ajax({
    type: 'POST',
    url: 'somelinkgoeshere.com',
    async: false,
    data: row,
    success: function(){console.log("Success")},
    error: function(){console.log("Error")}
});

ただし、これはブラウザをロックする可能性があるため、最善の方法ではありません。AJAXの全体的なポイントは非同期です。

于 2012-10-31T14:21:54.357 に答える