当前位置:Gxlcms > PHP教程 > javascript-ajax获取服务端的json数据出错了,JSON.parse(xhr.responseText),,,?

javascript-ajax获取服务端的json数据出错了,JSON.parse(xhr.responseText),,,?

时间:2021-07-01 10:21:17 帮助过:4人阅读

html页面:





无标题文档








php页面:

就是不能从服务端获取到json数据,报错如下:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

求解

回复内容:

html页面:





无标题文档








php页面:

就是不能从服务端获取到json数据,报错如下:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

求解

header的设置不对,这样设置输出的是utf-8格式的html,
使用

header('Content-type: application/json');

这样echo的数据即为json格式,
建议将要输出的内容存进数组,在要输出的地方使用

echo json_encode($array);

没试过,你试试不要直接这么写,换个写法,定义一个数组,然后json_encode()。

后端返回的格式不对

echo '{"code":"0","message":"该名字有人注册"}'

格式不对,json里面是双引号的。
这种

echo '{"code":"0","message":"该名字有人注册"}'

我在前台页面把从服务端获取到的结果输出`if(xhr.readyState == 4){

        if(xhr.status == 200){
            console.log(xhr.responseText);
            console.log(JSON.parse(xhr.responseText));
        }
    }`

在控制台看到是这样的(就是说xhr.responseText获取有问题吗?):

人气教程排行