Javascript "JSON.parse: unexpected character at line 2 column 1 of the JSON data"

Javascript "JSON.parse: unexpected character at line 2 column 1 of the JSON data"

我的 JSON 字符串看起来像这样

{"Peter":"35","Ben":"37","Joe":"43"} 

PHP代码

class Products{
    public function example(){
        $results = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
        echo json_encode($results);
    }
}

Javascript代码

const xhttp = new XMLHttpRequest();
xhttp.onload = function()
{
    const obj = this.responseText;
    const obj1 = JSON.parse(obj);
    alert(obj1);

}
xhttp.open("POST", "/products/example");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

我在 javascript 中解析问题时遇到错误。

当从 PHP 发送 JSON 时,您需要设置一个“Content-Type” Header 并且您不能使用 print_r.

<?php
$data=json_encode($result);
header('Content-Type: application/json');
echo $data;

尝试在浏览器的开发人员工具中查看您 PHP 脚本的响应,以确保您获得正确的 HTTP Content-Type header.