簡體   English   中英

Ajax呼叫正在等待另一個Ajax呼叫的響應?

[英]Ajax Call waiting for the response of another Ajax Call?

我有兩個無法在一個調用中完成的ajax調用。 當第一個ajax調用開始時,第二個ajax調用可以立即開始,或者只要用戶按下發送按鈕就可以開始。 如果第二個ajax調用開始,則他必須等待第一個ajax調用的響應,因為他需要從中獲取數據。

我如何才能實現第二個Ajax調用僅在第一個Ajax調用的響應到達后才發送他的請求?

  • 除了setTimeout之外,還有其他方法嗎?
  • 我可以以某種方式在ajax調用1上注冊ajax調用2的偵聽器嗎?

我的代碼是:

var xhrUploadComplete = false;

// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
    var returnedResponse = JSON.parse(response.responseText);
    xhrUploadComplete = true;
}
});

// ajax call 2
if (xhrUploadComplete) {
  $.ajax({
  url: url2,
  type: "POST",
  data: formdata2,
  processData: false,
  contentType: false,
  complete: function(response) {
    ...
  }
  });
}

編輯:第二個ajax調用不能發布在第一個調用的done()或complete()中,因為它取決於用戶選擇發送最終表單。 這兩個步驟的目的是在用戶將圖像插入到輸入type = file之后,將圖像發送到服務器。

編輯:知道我不能if(..),因為這是一個異步調用。 我寫它是為了清楚我需要做什么。 我想我需要Java的未來之類的東西。

xhrUploadComplete將異步地設置為true (將來,當請求完成時),因此您的if -condition(在請求開始后立即求值)將永遠無法實現。 您不能簡單地從ajax調用return (或設置)值 相反,將等待結果的代碼移到本應設置/返回變量的處理程序中:

$.ajax({
    url: url,
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    complete: function(response) {
        var returnedResponse = JSON.parse(response.responseText);
        $.ajax({
            url: url2,
            type: "POST",
            data: formdata2,
            processData: false,
            contentType: false,
            complete: function(response) {
                …
            }
        });
    }
});

使用Promise模式,您可以更優雅地組合它們:

$.ajax({
    url: url,
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false
}).then(function(response) {
    var returnedResponse = JSON.parse(response.responseText);
    return $.ajax({
        url: url2,
        type: "POST",
        data: formdata2,
        processData: false,
        contentType: false
    });
}).done(function(response) {
    // result of the last request
    …
}, function(error) {
   // either of them failed
});

也許您還需要這樣:

var ajax1 = $.ajax({
    url: url, …
}).then(function(response) {
    return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
    // as soon as ajax1 will be or has already finished
    ajax1.then(function(response1) {
        // schedule ajax2
        return $.ajax({
             url: url2, …
        })
    }).done(function(response) {
        // result of the last request
        …
    }, function(error) {
        // either of them failed
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM