Html page: {code...} php page: {code...} cannot obtain json data from the server. the error is as follows: {code...} solve the html page:
Untitled DocumentScript var oInput = document. getElementById ('input1'); var oDiv = document. getElementById ('p1'); 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
Php page:
Json data cannot be obtained from the server. the error is as follows:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Solution
Reply content:
Html page:
Untitled DocumentScript var oInput = document. getElementById ('input1'); var oDiv = document. getElementById ('p1'); 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
Php page:
Json data cannot be obtained from the server. the error is as follows:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Solution
Incorrect header settings. in this way, html in UTF-8 format is output,
Use
header('Content-type: application/json');
In this way, the echo data is in json format,
We recommend that you store the content to be output in an array.
echo json_encode($array);
I have never tried it. you should try not to write it directly. in another way, define an array and then json_encode ().
The format returned by the backend is incorrect.
Echo '{"code": "0", "message": "This name has been registered "}'
The format is incorrect. json contains double quotation marks.
This
Echo '{"code": "0", "message": "This name has been registered "}'
On the front-end page, I output the result obtained from the server 'if (xhr. readyState = 4 ){
if(xhr.status == 200){ console.log(xhr.responseText); console.log(JSON.parse(xhr.responseText)); } }`
You can see this in the console (that is, is there a problem with obtaining xhr. responseText ?) :