2010-11-30 48 views
3

我們知道只有使用$ .ajax和異步選項才能完成同步請求:false 但是我在Jquery手冊中看到,「同步請求可能暫時阻止瀏覽器 禁用請求處於活動狀態時的任何操作「。我有一些問題,如

我見過一些答案說使用回調()How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?。 我該如何實現這個功能。

在下面的函數中,如果請求失敗或者響應沒有返回我該如何處理它。我的意思是我可以使用「error:」還是類似的東西。 我怎樣才能改善這種功能efficently我的意思是使用回調和錯誤處理。據說(也不可能有錯誤和成功回撥一個請求)

function empvalidate() { 
      var exists = false;    // default return value is false 
      var empno = $("#empno").val(); 
      if (empno != '') { 
      $.ajax({ 
       url: "emp.php", 
       async: false, 
       dataType: "json", 
       data: {'param1': $("#param1").val(), 'empno': $("#empno").val()}, 
       success: function (data) { 
       exists = data.status;  // set status of existence to outer variable 
       } 
      }); 
      } 
      return exists;     // return actual value 
     } 
+0

請編輯該問題以使其更清晰,因爲這確實看起來像重複。你需要知道你鏈接的問題沒有回答什麼? – 2010-11-30 16:54:27

+0

@Jeff:我如何將回調函數與上面的代碼相關 – Someone 2010-11-30 17:06:11

回答

2

你同步的請求都將導致UI線程(因此瀏覽器)要等到XMLHttpRequest對象返回(類型無論它是失敗還是成功)。

jQuery將執行您的成功/完整和錯誤處理程序,就像您使用「正常」異步請求時執行的一樣。但是在它這樣做之前它會等待/阻止。

因此,最糟糕的情況是,實際的請求需要花費大量的時間。網絡延遲在這種情況下非常糟糕,大量的數據......所有這些將完全鎖定你的UI線程,這顯然是一個令人敬畏的用戶expierence。

我真的不知道現在有人應該在哪裏使用同步的ajax請求。

0

而不是使用async: false,你會更好做這樣的事情:

function begin_ajax() { 
    // Set your UI states here 
} 

function success_ajax(data) { 
    // Run whatever needs to run if the request is successful. 
} 

function error_ajax(xhr, error_type, msg) { 
    // Display error messages 
} 

function complete_ajax() { 
    // Clean up UI 
} 
$.ajax({ 
    beforeSend: begin_ajax, 
    success: success_ajax, 
    error: error_ajax, 
    complete: complete_ajax 
    // Your parameters here 
}); 
0

使用功能齊全,充分的理由

jQuery Docs

complete(XMLHttpRequest, textStatus) - Function

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", or "parsererror"). This is an Ajax Event.

「超時」

so代碼在你的ajax上看起來像這樣:

function empvalidate() { 
     var exists = false;    // default return value is false 
     var empno = $("#empno").val(); 
     if (empno != '') { 
     $.ajax({ 
      url: "emp.php", 
      async: false, 
      dataType: "json", 
      data: {'param1': $("#param1").val(), 'empno': $("#empno").val()}, 
      success: function (data, ts) { 

       if(ts == "success") 
        exists = data.status; // set status of existence to outer variable 
       else if(ts == "timeout") 
       { 
        $(document).trigger('customTimeoutHandler'); 
       } 
      } 
     }); 
     } 
     return exists;     // return actual value 
    } 

這裏不太確定應用程序,但請記住,您也可以在此處設置自定義超時變量。不太清楚你想要的是什麼,這取決於你的情況。