dongxun6458 2015-11-16 02: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-16 02: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"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?