How to make $.get() function synchronous in jQuery?

后端 未结 3 1052
时光取名叫无心
时光取名叫无心 2020-12-20 21:38

I want to make $.get() method synchronous in my function. In ajax aysnc : false helps me, now how do i do the same to to $.get()

va         


        
3条回答
  •  余生分开走
    2020-12-20 21:58

    Although already answered:

    $.ajax({
      method: 'GET',
      async: false
    });
    

    I want to warn of you the following:

    • Blocks javascript execution, and might thus lock the webpage (no buttons working etc etc, it looks like your page hangs during the ajax call)
    • Using synchronous calls gives console warnings.

    Javascript is build based on event-driven design. you could also fire an custom named event (with the data result in the event data) when the ajax/get call is complete and let the followup action listen to this event.

    eg:

    $(form).on('submit',function(){
       var formEl = this;
       $.get({...}).success(function(data){
         var event = new Event('data-submitted');
         event.data = data; 
         formEl.dispatchEvent(event);
       })
    });
    $(form).on('data-submitted',function(event){
      var data = event.data;
      // you can handle the post ajax request event here.
    });
    

提交回复
热议问题