jquery ajax synchronous call beforeSend

前端 未结 3 501
时光取名叫无心
时光取名叫无心 2021-02-08 06:06

I have a function called:

function callAjax(url, data) {
 $.ajax(
   {
     url: url, // same domain
     data: data,
     cache: false,
     async: false, // us         


        
相关标签:
3条回答
  • 2021-02-08 06:31

    This is what you are looking for - .ajaxStart()

    It will be triggered when any ajax event starts

    http://api.jquery.com/ajaxStart/

    They even give a specific example similar to what you are trying to accomplish:

     $("#loading").ajaxStart(function(){
       $(this).show();
     });
    

    You can then use the .ajaxStop() function

    $("#loading").ajaxStop(function(){
          $(this).hide();
    });
    
    0 讨论(0)
  • 2021-02-08 06:40

    When you do the blocking I/O the program is halted until the the input is received, in JS words when doing a synchronous call, the program halts and browser window freezes (no painting can be done) until the response is received. In most cases doing syncronus calls and any kind of blocking I/O can be avoided. However imagine your doing a progress bar in java or any other programming language, you have to spawn a different thread to control the progress bar, I think.

    One thing to try in your case, is to call the ajax call after a time delay

    //loading div stuff, 
    //if your doing some animation here make sure to have Sufficient 
    //time for it. If its just a regular show then use a time delay of 100-200
    setTimeout( ajaxCall, 500 );
    

    EDIT ajaxcall in setTimeout, Example

    0 讨论(0)
  • 2021-02-08 06:42

    Making a synchronous call like that is like putting up an "alert()" box. Some browsers stop what they're doing, completely, until the HTTP response is received.

    Thus in your code, after your call to the "$.ajax()" function begins, nothing happens until the response is received, and the next thing as far as your code goes will be the "success" handler.

    Generally, unless you're really confident in your server, it's a much better idea to use asynchronous calls. When you do it that way, the browser immediately returns to its work and simply listens in the background for the HTTP response. When the response arrives, your success handler will be invoked.

    0 讨论(0)
提交回复
热议问题