AJAX数据变量未加载

时间:2011-12-08 17:31:55

标签: jquery ajax jplayer

我有一个AJAX语句,用于返回PHP脚本的回显输出,输出是XML。

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

AJAX请求中的“data”变量未正确返回,即使firebug网络选项卡显示状态200 ok请求。

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脚本输出的XML相同 link

1 个答案:

答案 0 :(得分: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...
];