>  기사  >  백엔드 개발  >  javascript - 서버 JSON.parse(xhr.responseText)에서 json 데이터를 가져오는 중 Ajax 오류가 발생했습니다.,,?

javascript - 서버 JSON.parse(xhr.responseText)에서 json 데이터를 가져오는 중 Ajax 오류가 발생했습니다.,,?

WBOY
WBOY원래의
2016-12-01 00:25:451888검색

html 페이지:

<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 페이지:

<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>

서버에서 json 데이터를 가져올 수 없으며 오류는 다음과 같습니다.

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

솔루션

답글 내용:

html 페이지:

<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 페이지:

<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>

서버에서 json 데이터를 가져올 수 없으며 오류는 다음과 같습니다.

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

솔루션

헤더 설정이 잘못되었습니다. 이 설정은 HTML을 UTF-8 형식으로 출력합니다.

을 사용하세요.
<code>header('Content-type: application/json');</code>

이렇게 에코 데이터가 json 형식이 됩니다.
출력할 내용을 배열로 저장하고, 출력할 곳에는

을 사용하는 것이 좋습니다.
<code>echo json_encode($array);</code>

아직 시도해보지 않았습니다. 이렇게 직접 작성하지 말고 다르게 작성하고 배열을 정의한 다음 json_encode()를 작성하세요.

백엔드에서 반환된 형식이 올바르지 않습니다

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

형식이 잘못되었습니다. json에 큰따옴표가 있습니다.
이런

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

서버에서 얻은 결과를 첫 페이지 `if(xhr.readyState == 4){

에 출력합니다.
<code>        if(xhr.status == 200){
            console.log(xhr.responseText);
            console.log(JSON.parse(xhr.responseText));
        }
    }`</code>

콘솔에 표시되는 내용입니다(즉, xhr.responseText를 얻는 데 문제가 있습니까?). javascript - 서버 JSON.parse(xhr.responseText)에서 json 데이터를 가져오는 중 Ajax 오류가 발생했습니다.,,?

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:WeChat 개발 문제다음 기사:WeChat 개발 문제