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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀