开发者

Performing synchronus Requests using $.ajax

we know that only synchrnous requests are done with $.ajax with an option of async:false But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synch开发者_如何学编程ronous, rather than asynchronous, Ajax request?. How can i implement this to my function .

In the below Function if the Request Fails or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that . How can I improve this Function efficently i mean using call back and error handling .It is said that (we can never have error and success call back with a request)

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
        }


Your synchronized request will cause the UI thread (and therefore the browser) to wait until the XMLHttpRequest object returns (kind regardless whether it failed or succeded).

jQuery will execute your success / complete and error handler the same way it would execute when you're using a "normal" asynchronous request. But it will wait / block before it does so.

So the worst case scenario here would be, that the actual request takes a huge amount of time. Network latencys are pretty bad in this context, large data amounts.. all those will entirely lock up your UI thread which is obviously an aweful user expierence.

I really don't know where someone should use a synchronized ajax request nowadays.


Rather than using async: false, you'd be better off doing something like this:

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
});


Use the complete function and make a case for "timeout"

from 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 Code would look something like this on your 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
    }

Not really sure of the application here, but remember that you can also set a custom timeout variable here too. Not too sure what you would want it to be, it just depends on your scenario.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜