簡體   English   中英

$ .ajax調用后(即服務器正在處理AJAX請求時)如何停止執行JS代碼

[英]How to Stop execution of the JS Code after $.ajax call i.e. when server is processing the AJAX Request

我在JQuery AJAX中遇到一個奇怪的問題。

我的步驟順序如下:

1)我有一個JS函數,我在Button Click事件上調用:

 function Click()
 {

    //I am performing some Validations then making an AJAX Request:

   $.ajax({
      type: "POST", 
      url: url, 
      context: window, 
      data: datatoPost,
      contentLength: contentLength, 
      async: true, 
      success: function (response) { 
          callbackFn(response); 
       },
      error: function (msg) { 
          this.error = msg;
       }
    });

   // The callback function is called on Successfull AJAX Request 
   // i.e. callbackFn (See below)

   // I am then checking the window.IsValid which I have set in below function;

   if (window.IsValid == true) {
           // Then Perform another AJAX Request
     }
     else {
         // do nothing
     }
  }


  function callbackFn(response)
  {
     if(response == 'Valid')
     {
         window.IsValid = true;
     }
     else 
     {
         window.IsValid = false;
     }
  }

2)現在,問題出在服務器正在處理第一個AJAX請求時,然后在此之后編寫的代碼即if(window.IsValid == true){//然后執行另一個AJAX請求} else {//不執行任何操作}}

3)我得到window.IsValid = false作為第一個AJAX請求的回調函數,即尚未調用callbackFn(response) ,即使在第一個AJAX請求的有效響應之后,我的第二個Ajax請求也沒有作為window.IsValid變量執行已在回調函數中設置,因為由於服務器正在處理請求,因此尚未調用回調。

請幫助我,我被卡住了。

然后,您應該使用

async: false,

在您的ajax函數調用中。 不建議這樣做。 更好的是使用

if (window.IsValid == true) {
           // Then Perform another AJAX Request
     }
     else {
         // do nothing
     }
  }

在您的回調函數中。

因為您的帖子是異步的,所以腳本在處理ajax請求的同時繼續執行。

相反,您需要將window.IsValid的測試移到成功函數中:

function Click()
{
   //I am performing some Validations then making an AJAX Request:

   $.ajax({
      type: "POST", 
      url: url, 
      context: window, 
      data: datatoPost,
      contentLength: contentLength, 
      async: true, 

      success: function (response) { 
          callbackFn(response); 

          if (window.IsValid == true) {
              // Then Perform another AJAX Request 
              // best done as another function.
          }
          else {
              // do nothing
          }
       },

      error: function (msg) { 
          this.error = msg;
      }
   });
}

暫無
暫無

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

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