php無(wú)法返回json格式的解決辦法:1、判斷error的具體原因,執(zhí)行“var a=JSON.stringify(error);alert(a);”代碼;2、修改php代碼,執(zhí)行“var b= eval("(" + data + ")");”代碼即可。
本教程操作環(huán)境:Windows10系統(tǒng)、PHP8.1版、DELL G3電腦
php無(wú)法返回json格式怎么辦?
php無(wú)法返回標(biāo)準(zhǔn)JSON格式:導(dǎo)致的$.ajax返回的數(shù)據(jù)無(wú)法執(zhí)行success的解決方案
JSON的標(biāo)準(zhǔn)格式:{“鍵”:“值”,“鍵”:“值”}
一、前端提交代碼,如下
$.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); }});
二、PHP后臺(tái)處理后,返回代碼:
$res['err'] = "歡迎您"; $res['codeId'] = "1";
console.log(data),可知為:{err:“輸入密碼錯(cuò)誤!”,codeId:“0”},代碼鍵無(wú)雙引號(hào),非標(biāo)準(zhǔn)JSON格式,會(huì)導(dǎo)致$.ajax返回的數(shù)據(jù)無(wú)法執(zhí)行success。
三、分析如下:
-
判斷error的具體原因,因返回的是[object object]對(duì)象格式,需要轉(zhuǎn)為字符串格式,以便快速的查找原因:
var a=JSON.stringify(error); alert(a);
如果是格式不正確的話,基本上返回的錯(cuò)誤代碼為:readyState=4,status=200。
-
一是修改php代碼,直接返回標(biāo)準(zhǔn)的JSON格式,因漏刻有時(shí)數(shù)據(jù)可視化代碼格式化的原因,本例采用返回前端進(jìn)行解決;
返回類型為:dataType: “text”,
返回后格式為:{“err”:“輸入密碼錯(cuò)誤!”,“codeId”:“0”},進(jìn)行typeof(),可知為string格式,需要將字符串轉(zhuǎn)化為JSON,采用eval函數(shù):
eval() 函數(shù)用來(lái)執(zhí)行一個(gè)字符串表達(dá)式,并返回表達(dá)式的值 ——來(lái)源于菜鳥教程
var b= eval("(" + data + ")");//一定按照該格式才是標(biāo)準(zhǔn)的JSON格式
完整的前端提交和返回代碼:
$.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") {//讀取鍵值進(jìn)行判斷 alert(b.err); } else { alert(b.err); window.location.href = "index.php?m=Index&a=lockData";//跳轉(zhuǎn)頁(yè)面; } }, error:function(error){ var a=JSON.stringify(error);//解析對(duì)象為字符串,快速確定原因; alert(a); }});
Done!
推薦學(xué)習(xí):《PHP視頻教程》