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

html页面:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>

</head>

<body>
<form action="reg.php" method="post" >
    用户名 : <input id="input1" type="text" name="username">   
    <input type="submit" value="注册">
</form>
<div id="div1"></div>
<script>
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');

oInput.onblur = function(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET','ajax.php?username='+encodeURIComponent(this.value),true);
    xhr.onreadystatechange = function(){
        
        if(xhr.readyState == 4){
            
            if(xhr.status == 200){
                
                var obj = JSON.parse(xhr.responseText);
                if(obj.code){
                    oDiv.innerHTML = obj.message;
                }
                else{
                    oDiv.innerHTML = obj.message;
                }
            }
        }
        
    };
    xhr.send(null);
};

</script>
</body>
</html>

php页面:

<?php
    header('Content-type:text/html;charset=utf-8');
    $conn = mysqli_connect('127.0.0.1', 'root', '5221107073', 'linshi');
    $name = $_GET['username'];
    $sql = "SELECT * FROM shi where name='$name'";
    $res = mysqli_query($conn, $sql);
    if($res && mysqli_num_rows($res)){
        echo "{'code':'0','message':'该名字有人注册'}";
    }else{
        echo "{'code':'1','message':'ok'}";
    }
    
?>

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

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

求解

阅读 8.6k
6 个回答

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获取有问题吗?):图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题