2013-03-28 43 views
2

我有以下腳本到一個新的價值添加到我的會話變量的數組,並告訴我varible完全實時會話如何完成加載條件,一個函數在jQuery中執行另一個函數?

(function ($) { 

    Drupal.behaviors.MyfunctionTheme = { 
     attach: function(context, settings) { 

    $('.add-music').click(function() { 
     var songNew = JSON.stringify({ 
      title: $(this).attr('data-title'), 
      artist: $(this).attr('data-artist'), 
      mp3: $(this).attr('href') 
     }); 
     var songIE = {json:songNew}; 
     $.ajax({ 
      type: 'POST', 
      data: songIE, 
      datatype: 'json', 
      async: true, 
      cache: false 
     }); 

     var session; 
     $.ajaxSetup({cache: false}) 
     $.get('/getsession.php', function (data) { 
      session = data; 
      alert(session); 
     }); 

    }); 

}} 

})(jQuery); 

的問題是,POST運輸時間比調用GET ALERT不再那麼顯示未更新的會話變量。

有沒有辦法只在POST完成時纔將IF條件寄送回來I GET?

感謝

回答

3

其實,你要不要做的是使用一個回調 - 也就是說,一個被立即調用作爲POST Ajax請求返回的功能。

例子:

(function ($) { 

    Drupal.behaviors.MyfunctionTheme = { 
     attach: function(context, settings) { 

    $('.add-music').click(function() { 
     var songNew = JSON.stringify({ 
      title: $(this).attr('data-title'), 
      artist: $(this).attr('data-artist'), 
      mp3: $(this).attr('href') 
     }); 
     var songIE = {json:songNew}; 
     $.ajax({ 
      type: 'POST', 
      data: songIE, 
      datatype: 'json', 
      async: true, 
      cache: false     
     }) 
     .done(
       //this is the callback function, which will run when your POST request returns 
      function(postData){ 
       //Make sure to test validity of the postData here before issuing the GET request 
       var session; 
       $.ajaxSetup({cache: false}) 
       $.get('/getsession.php', function (getData) { 
         session = getData; 
         alert(session); 
       }); 

       } 
     ); 

    }); 

}} 

})(jQuery); 

更新每伊恩的好建議,我已經取代了過時的成功()函數用新的有()語法

UPDATE2我已經納入另一個偉大的建議from radi8

+1

打敗我吧。你可能想要建議'.done()'方法取代'$ .ajax'的'success'選項 - '$ .ajax({})。done(function(){});' – Ian

+1

success:function (){...});折舊,所以使用done:function(){...});.請務必在處理GET之前測試返回的值是否有效。 – radi8

+1

你是對的!我已經更新了我的回答 – OpherV

相關問題