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

后端 未结 3 1026
时光取名叫无心
时光取名叫无心 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:49

    add an object parameter

    $.get({
    url: 'your-url',
    async:false
    });
    
    0 讨论(0)
  • 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.
    });
    
    0 讨论(0)
  • 2020-12-20 22:11

    $.get also accepts parameter like this

    $.get({
      url: url,// mandatory
      data: data,
      success: success,
      dataType: dataType,
      async:false // to make it synchronous
    });
    
    0 讨论(0)
提交回复
热议问题