2011-12-08 34 views
0

我有一个AJAX语句,用于返回来自PHP脚本的回显输出,输出是XML。AJAX数据变量无法加载

如果直接导航到PHP脚本,它会以我需要的确切格式输出JSON。

AJAX请求中的“数据”变量没有正确返回,即使萤火虫网络选项卡表示状态200可以请求。

的PHP返回XML元素 “MP3和标题”

<?php 
    $url = 'http://www.startalkradio.net/?page_id=354'; 
    $rss = simplexml_load_file($url); 
    $items = $rss->channel->item; 

    $i = 0; 
    $data = array(); 
    foreach ($items as $item) { 
     $data[] = array(
      'title' => (string) $item->title, 
      'mp3' => (string) $item->enclosure['url'], 
     ); 
     if (++$i == 3) break; 
    } 

    $jsdata = json_encode($data); 
    echo htmlspecialchars($jsdata, ENT_NOQUOTES, 'utf-8'); 
?> 

AJAX调用填充JPlayer脚本。 data似乎没有被退回。

$(document).ready(function() { 
    $.get(
     "http://www.freeenergymedia.com/getxml2.php", 
     function(data) { 
      new jPlayerPlaylist({ 
       jPlayer: "#jquery_jplayer_1", 
       cssSelectorAncestor: "#jp_container_1" 
      }, 
      data, 
      {  <!-- here I am returning the php script to populate XML into JPlayer. --> 
       swfPath: "js", 
       supplied: "mp3, oga", 
       wmode: "window" 
      }); 
     } 
    ); 
}); 

问题

这里link是工作笔记版本的XML是一样的东西是由PHP脚本输出 link

+1

你有没有试过需要指明的数据类型为XML? http://api.jquery.com/jQuery.get/,第四个参数是dataType。您也可以切换到$ .ajax方法,以便绑定错误事件。此外,你可以console.log(数据);在你的函数内部看看响应是什么。 –

+0

现在试图 –

+0

http://www.freeenergymedia.com/getxml2.php返回的JSON不是XML。 –

回答

1

你说你正在返回的XML,但你的PHP使用json_encode()。所以,你的电话$.get()应当规定:

//using `$.getJSON()` will set the dataType property to json so your server-side output will be parsed into a JavaScript object 
$.getJSON(
     "http://www.freeenergymedia.com/getxml2.php", 
     function(data) { 
      console.log(data);//<--use this to inspect the JSON object returned from the server, make sure it's in the proper format 
      new jPlayerPlaylist({ 
       jPlayer: "#jquery_jplayer_1", 
       cssSelectorAncestor: "#jp_container_1" 
      }, 
      data, 
      {  <!-- here I am returning the php script to populate XML into JPlayer. --> 
       swfPath: "js", 
       supplied: "mp3, oga", 
       wmode: "window" 
      }); 
     } 
    ); 

data应该是这个样子:

data = [ 
    {"title":"some title", "mp3":"path to some song"}, 
    {"title":"some other title", "mp3":"path to some other song"}, 
    etc... 
]; 
+0

$ .get方法还允许用户指定期望“数据”的格式。只要在使用$ get时指定dataType,$ .getJSON和$ .get就会工作 –