鍍金池/ 問答/PHP  HTML/ jquery ajax無法獲取回調(diào)json ,并且報(bào)parsererror錯(cuò)誤

jquery ajax無法獲取回調(diào)json ,并且報(bào)parsererror錯(cuò)誤

各種百度說這個(gè)錯(cuò)誤是因?yàn)閖son格式不標(biāo)注引起的

這是后端php 用json_encode函數(shù)生成的json

clipboard.png

看了jquery的官方文檔似乎沒錯(cuò)
jQuery.parseJSON( json )
Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:

{test: 1} (test does not have double quotes around it). 譯:test兩邊必須有雙引號(hào) {"test":1}
{'test': 1} ('test' is using single quotes instead of double quotes). 譯:test兩邊的引號(hào)不能為單引號(hào),一定要是雙引號(hào)
Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.

而且以前一直都是這么返回的都沒有出錯(cuò),請(qǐng)問那么正確的json標(biāo)準(zhǔn)格式應(yīng)該是怎樣的?

回答
編輯回答
孤影
  1. jQ里的ajax,如果明確寫了dataType: "json"或者用的是getJSON的話,返回的data(參數(shù))可以直接當(dāng)對(duì)象用,不用轉(zhuǎn)換
  2. php里的json_encode有個(gè)小坑,用的時(shí)候需要把第二參數(shù)指定為JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK,這個(gè)在官方文檔的JSON常量里有例程說明(評(píng)論里),不加這個(gè)的話,php會(huì)做自動(dòng)轉(zhuǎn)換,拿到的json不是帶斜線就是unicode被自動(dòng)轉(zhuǎn)換。另外后端返回其它奇怪的json也可以看看常量這塊。
2017年3月21日 22:06
編輯回答
慢半拍

代碼示例
clipboard.png

拋出的錯(cuò)誤彈窗

clipboard.png

clipboard.png

clipboard.png

clipboard.png

2017年5月26日 23:50
編輯回答
艷骨

如果看起來沒錯(cuò),那就把整個(gè)字符串都按字符打印編碼,看看有沒有不可見字符比如 BOM。

2018年4月11日 05:39