2012-03-12 98 views
0

返回JSON可变我有功能:我无法从jQuery的AJAX功能

function get_playlist(){  

     var result = jQuery.ajax({ 
      url: '<?php echo admin_url('admin-ajax.php'); ?>', 
      type: 'post', 
      dataType: 'json', 
      data: { 
       action: 'getrandommp3', 
       nonce:'<?php echo wp_create_nonce('randmp3'); ?>' 
      }, 
      success: function(response) { 
       console.log(response); // All OK! 
       window.response = response; 
       var customvar = response; 
       return response; 
      }    
     }); 
     console.log(window.response); // undefined 
     console.log(result.responseText); //undefined 
     console.log(customvar); //undefined 
     return window.response; // returning undefined 
    } 

我需要从函数返回JSON变量。里面有success: function(response) {响应有需要的内容。但Jquery.ajax我有问题外...

此代码需要jQuery的MP3播放器...

var playlist = get_playlist(); 
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options); 
myPlaylist.shuffle(true, true); 

感谢您的帮助!

回答

2

这是AJAX的工作方式(异步)。 success事件处理程序之外的console.log语句在返回响应之前执行(因此尚未将任何内容分配给window.response)。将依赖于AJAX响应的代码放入success事件处理程序中。

或者,您可以使请求同步,但这通常不是您想要的,因为它可以锁定浏览器直到返回响应。

更新(查看评论和编辑质疑)

正如我前面提到的,你需要把它依赖于准备事件处理程序内的AJAX响应的所有代码:

function get_playlist(){  
    var result = jQuery.ajax({ 
     //Other AJAX options removed 
     success: function(response) { 
      var myPlaylist = new jPlayerPlaylist(cssSelector, response, options); 
      myPlaylist.shuffle(true, true); 
     }    
    }); 
} 
+0

我有jquery播放器,我需要返回json mp3的清单。 'var playlist = get_playlist(); \t \t \t var myPlaylist = new jPlayerPlaylist(cssSelector,playlist,options); \t \t \t myPlaylist.shuffle(true,true);' – 2012-03-12 10:01:50

+0

然后在'success'事件处理程序中创建'jPlayer'。看我的编辑。 – 2012-03-12 10:03:20

+0

谢谢你的帮助) – 2012-03-12 10:08:28