簡體   English   中英

Ajax jquery同步回調成功

[英]Ajax jquery synchronous callback success

我有這個函數進行ajax調用。 我在最后一段代碼注釋中描述了這個問題。

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

根據代碼注釋中描述的問題,哪種更改最適合這種情況?

您需要為同步請求設置async:false,如下所示:

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

看到這里了解詳細信息

將scax指向的Ajax調用設置為synchronous,或者只是將代碼移動到成功回調中。 你為什么不能這樣做? 即使它是另一個Ajax調用它仍然可以完成 - 你可以嵌套它們。 到目前為止您提供的信息(我看不到有問題的代碼,也沒有足夠的關於您的項目的領域知識)我真的沒有看到問題。

我更喜歡使用回調來完成這項工作,因為它實現了完全相同的結果而沒有實際使它同步。 我使用成功:回調然后傳入回調作為參數。

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

然后我調用這個函數:

  getData(function(data){
    console.log(data); //do something 
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM