Home  >  Article  >  Backend Development  >  javascript - Ajax error in obtaining json data from the server, JSON.parse(xhr.responseText),,,?

javascript - Ajax error in obtaining json data from the server, JSON.parse(xhr.responseText),,,?

WBOY
WBOYOriginal
2016-12-01 00:25:451888browse

html page:

<code><!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></code>

php page:

<code><?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'}";
    }
    
?></code>

It means that the json data cannot be obtained from the server, and the error is as follows:

<code>SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data</code>

Solve

Reply content:

html page:

<code><!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></code>

php page:

<code><?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'}";
    }
    
?></code>

It means that the json data cannot be obtained from the server, and the error is as follows:

<code>SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data</code>

Solve

The header setting is wrong. This setting outputs html in utf-8 format.
Use

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

In this way, the echo data is in json format.
It is recommended to save the content to be output into an array and use it where it is to be output.

<code>echo json_encode($array);</code>

I haven’t tried it. Try not to write it directly like this. Instead, write it differently, define an array, and then json_encode().

The format returned by the backend is wrong

<code class="php">echo '{"code":"0","message":"该名字有人注册"}'</code>

The format is wrong, there are double quotes in json.
This kind

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

I output the results obtained from the server on the front page `if(xhr.readyState == 4){

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

This is what you see on the console (that is, is there a problem with obtaining xhr.responseText?): javascript - Ajax error in obtaining json data from the server, JSON.parse(xhr.responseText),,,?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:WeChat development issuesNext article:WeChat development issues