简体   繁体   中英

Ajax jquery synchronous callback success

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 = this;
            var theold = "theold";
            var thenew = "thenew";

            $.ajax({
                    url: 'doop.php',
                    type: 'POST',
                    data: 'before=' + theold + '&after=' + thenew,
                    success: function(resp) {
                            if(resp == 1) {
                                    $(that).siblings('.theold').html(thenew);
                            }
                    }
            });

            // I have some code here (out of the ajax) that **further** changes 
            // the .theold's html beyond what it was changed inside ajax success
            // but the change depends on whether the resp (inside the success 
            // function) returned 1 or not, so this code out here depends on the ajax
            // so it looks like I have to turn this ajax call into a sync ajax

            return false;
    }

Based on the problem as described in the code comments, what changes are best for this situation?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM