2011-12-08 37 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就會工作 –