dongxun6458 2015-11-15 18:01
浏览 46
已采纳

无法解析JSON(xmlhttp)

I've gone through literally all of the other questions on this topic but I can't seem to find a fix for this relatively easy problem:

console.log(xmlhtpp.responseText) results in:

[{"id":"1","name":"Filosofie","image":"yin-yang.png","background_color":"no"},{"id":"2","name":"Politiek","image":"politics.png","background_color":"no"},{"id":"3","name":"Geschiedenis","image":"history.png","background_color":"no"},{"id":"4","name":"Vocabulaire","image":"vocabulary.png","background_color":"no"},{"id":"5","name":"Wetenschap","image":"science.png","background_color":"no"}]

The problem occurs when I try to parse the string to an object like so:

JSON.parse(xmlhttp.responseText);

Which results in the following error:

Uncaught SyntaxError: Unexpected end of input

The string originates from a PHP file:

$results = $db->query("SELECT * FROM library ORDER BY id", true);   

$categories = array();

while ($row = mysqli_fetch_assoc($results)) {
    $categories[] = $row;
}

echo json_encode($categories);

I need to loop trough the object eventually but I can't get past the parsing, any advice would be very much appreciated.

  • 写回答

1条回答 默认 最新

  • dqn48247 2015-11-15 18:25
    关注

    The default Content-Type from XAMPP is text/html, so your browser is trying to parse it like this..

    Set the content-type yourself..

    header('Content-Type: text/javascript');
    echo json_encode(["foo", "bar"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部