Ajax jquery synchronous callback success

前端 未结 3 1316
说谎
说谎 2020-12-11 07:25

I have this function that makes an ajax call. I\'m describing the problem in the last chunk of code comments.

    function doop(){
            var that = thi         


        
相关标签:
3条回答
  • 2020-12-11 08:12

    Either set the Ajax call to synchronous as stefita pointed out, or just move your code into the success callback. Why can't you do this? Even if it's another Ajax call it still can be done - you can nest them. With the information given by you so far (I can't see the problematic code, nor I have enough domain knowledge about your project) I don't see a problem, really.

    0 讨论(0)
  • 2020-12-11 08:14

    I prefer to use callback to do the job because it achieves exactly the same result without actually making it synchronous. I use success:callback and then pass in the callback as a parameter.

     function getData(callback) {
          $.ajax({
              url: 'register/getData',
              data: "",
              dataType: 'json',
              success: callback
          });
      }
    

    I then call this function like this:

      getData(function(data){
        console.log(data); //do something 
      });
    
    0 讨论(0)
  • 2020-12-11 08:18

    You need to set async: false for synchronous requests like this:

    function doop(){
            var that = this;
            var theold = $(this).siblings('.theold').html();
            var thenew = $(this).siblings('.thenew').val();
    
            $.ajax({
                    async: false,
                    url: 'doop.php',
                    type: 'POST',
                    data: 'before=' + theold + '&after=' + thenew,
                    success: function(resp) {
                            if(resp == 1) {
                                    $(that).siblings('.theold').html(thenew);
                            }
                    }
            });
    
            // some other code
    
            return false;
    }
    

    see here for details

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