2

我有以下脚本来向我的会话变量的数组添加一个新值,并向我展示完全实时会话的变量

(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 花费的时间更长,然后显示会话变量未更新。

有没有办法设置一个 IF 条件仅在 POST 完成时才返回我 GET 的响应?

谢谢

4

1 回答 1

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

根据 Ian 的好建议更新我已经用新的 done() 语法替换了不推荐使用的 success() 函数

更新 2 我采纳了 radi8 的另一个好建议

于 2013-03-28T18:11:16.207 回答