php無法返回json格式的解決辦法:1、判斷error的具體原因,執行“var a=JSON.stringify(error);alert(a);”代碼;2、修改php代碼,執行“var b= eval("(" + data + ")");”代碼即可。
本教程操作環境:Windows10系統、PHP8.1版、DELL G3電腦
php無法返回json格式怎么辦?
php無法返回標準JSON格式:導致的$.ajax返回的數據無法執行success的解決方案
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) { 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后臺處理后,返回代碼:
$res['err'] = "歡迎您"; $res['codeId'] = "1";
登錄后復制
console.log(data),可知為:{err:“輸入密碼錯誤!”,codeId:“0”},代碼鍵無雙引號,非標準JSON格式,會導致$.ajax返回的數據無法執行success。
三、分析如下:
-
判斷error的具體原因,因返回的是[object object]對象格式,需要轉為字符串格式,以便快速的查找原因:
var a=JSON.stringify(error); alert(a);
登錄后復制
如果是格式不正確的話,基本上返回的錯誤代碼為:readyState=4,status=200。
-
一是修改php代碼,直接返回標準的JSON格式,因漏刻有時數據可視化代碼格式化的原因,本例采用返回前端進行解決;
返回類型為:dataType: “text”,
返回后格式為:{“err”:“輸入密碼錯誤!”,“codeId”:“0”},進行typeof(),可知為string格式,需要將字符串轉化為JSON,采用eval函數:
eval() 函數用來執行一個字符串表達式,并返回表達式的值 ——來源于菜鳥教程
var b= eval("(" + data + ")");//一定按照該格式才是標準的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") {//讀取鍵值進行判斷 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!
推薦學習:《PHP視頻教程》