2009-10-15 72 views
4

我有這個函數,使ajax調用。我在最後一段代碼註釋中描述了這個問題。Ajax jquery同步回調成功

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

基於代碼註釋中描述的問題,哪種更改最適合這種情況?

回答

15

您需要設置異步:假的同步請求是這樣的:

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

看到here的細節

+0

我一直在讀,設置'異步:FALSE'是壞的,一個'callback'更好。但我懷疑這很簡單。根據我更新的問題,你推薦哪一種? – Chris 2009-10-15 14:21:56

+3

嗯,實際上你聲明的成功屬性函數是回調函數。順便說一下,我剛纔看到你將結果與一個整數進行比較,但我確定你默認獲得了文本,所以它應該是'resp ==「1」'。 – stefita 2009-10-15 14:40:02

+2

btw。你可以在ajax請求之外的地方定義你的回調函數。可能是你看到的就是這個 - 一個叫做回調的函數。 – stefita 2009-10-15 14:42:01

1

即可以將Ajax調用爲同步爲stefita指出的,或只是移動你的代碼成功回調。你爲什麼不能這樣做?即使這是另一個Ajax調用,它仍然可以完成 - 你可以將它們嵌套。有了你迄今給出的信息(我看不到有問題的代碼,也沒有足夠的關於你的項目的領域知識),我真的沒有看到問題。

+0

我明白了,所以$(.ajax)調用可以嵌套。聽起來不錯,我會嘗試一下,看看它是如何運作的。 – Chris 2009-10-15 14:24:57

0

我更喜歡使用回調來完成這項工作,因爲它實現了完全相同的結果,但實際上並未實現同步。我使用success:callback,然後將回調作爲參數傳入。

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

我再調用這個函數是這樣的:

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