Solution to the problem that php cannot return json format: 1. Determine the specific cause of the error and execute the "var a=JSON.stringify(error);alert(a);" code; 2. Modify the php code and execute "var b= eval("(" data ")");" code is enough.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer
What should I do if php cannot return json format? ?
php cannot return the standard JSON format: the data returned by $.ajax cannot perform success solution
Standard format of JSON: {"key":"value","key":"value"}
1. Front-end submission code, as follows
$.ajax({ type: "post", url: "index.php?m=Index&a=accessIn&act=access", async: true, data: { login_access: $('#login_access').val() }, dataType: "text", success: function (data) { if (data.codeId == "0") { alert(data.err); } else { alert(data.err); window.location.href = "index.php?m=Index&a=lockData"; } }, error:function(error){ var a=JSON.stringify(error); alert(a); }});
2. After PHP background processing, the return code is:
$res['err'] = "欢迎您"; $res['codeId'] = "1";
console.log(data), which can be seen as: {err: "Wrong password entered!", codeId: "0"}, code The key does not have double quotes and is in non-standard JSON format, which will cause the data returned by $.ajax to fail.
3. The analysis is as follows:
Determine the specific cause of the error. Since the returned object format is [object object], it needs to be converted to string format for quick processing. Find the reason:
var a=JSON.stringify(error); alert(a);
If the format is incorrect, the error code returned is basically: readyState=4, status=200.
The first is to modify the php code and directly return the standard JSON format. Due to the missing data visualization code formatting, this example uses returning to the front end to solve the problem;
The return type is :dataType: "text",
The returned format is: {"err": "Wrong password entered!", "codeId": "0"}, perform typeof(), it can be seen that it is in string format, and the string needs to be Convert to JSON, use the eval function:
eval() function is used to execute a string expression and return the value of the expression - from novice tutorial
var b= eval("(" + data + ")");//一定按照该格式才是标准的JSON格式
Full front-end commit and return code:
$.ajax({ type: "post", url: "index.php?m=Index&a=accessIn&act=access", async: true, data: { login_access: $('#login_access').val() }, dataType: "text", success: function (data) { var b= eval("(" + data + ")");//string 2 json if (b.codeId == "0") {//读取键值进行判断 alert(b.err); } else { alert(b.err); window.location.href = "index.php?m=Index&a=lockData";//跳转页面; } }, error:function(error){ var a=JSON.stringify(error);//解析对象为字符串,快速确定原因; alert(a); }});
Done!
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What should I do if php cannot return json format?. For more information, please follow other related articles on the PHP Chinese website!