() 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.getElementByIdinput1;
var oDiv = document.getElementByIddiv1; oInput.onblur = function{ var xhr = new XMLHttpRequest; xhr.openGET,ajax.php?username=+encodeURIComponentthis.value,true; xhr.onreadystatechange = function{ ifxhr.readyState == 4{ ifxhr.status == 200{ var obj = JSON.parsexhr.responseText; ifobj.code{ oDiv.innerHTML = obj.message; } else{ oDiv.innerHTML = obj.message; } } } }; xhr.sendnull;
}; </script>
</body>
</html>

php页面:

<?php headerContent-type:text/html;charset=utf-8; $conn = mysqli_connect127.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

求解

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

后端返回的格式不对

发表评论

电子邮件地址不会被公开。 必填项已用*标注