无法解析 JSON (xmlhttp)

Unable to parse JSON (xmlhttp)

我几乎已经解决了关于这个主题的所有其他问题,但我似乎无法找到解决这个相对简单问题的方法:

console.log(xmlhtpp.responseText) 结果:

[{"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"}]

当我尝试将字符串解析为对象时出现问题:

JSON.parse(xmlhttp.responseText);

这会导致以下错误:

Uncaught SyntaxError: Unexpected end of input

字符串源自 PHP 文件:

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

$categories = array();

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

echo json_encode($categories);

我最终需要遍历对象,但我无法通过解析,任何建议将不胜感激。

XAMPP 的默认 Content-Type 是 text/html,因此您的浏览器正在尝试像这样解析它..

自己设置内容类型..

header('Content-Type: text/javascript');
echo json_encode(["foo", "bar"]);