[英]jQuery JSON Parsing Error
我有一個 web 頁面,該頁面在調用時返回此 JSON:
[{"id":"53","desc":"Roberts"}]
我正在使用這個 jQuery 通過 AJAX 調用它:
$.ajax ({
url: rootPath + "data/topology/stations",
dataType: 'json',
data: { areaID: $("#lbxArea").val () },
success: function (data) {
// Use data for actions
},
error: function (jqXHR, textStatus, errorThrown) {
alert (textStatus);
alert (errorThrown);
}
});
我使用 Firebug 來確認返回的數據是我放在最上面的數據。 盡管如此,我還是陷入了error
回調,首先在警報框中看到parsererror
,然后我看到
SyntaxError: JSON.parse: expected property name or '}'
我嘗試讓服務返回
{"list":[{"id":"53","desc":"Roberts"}]}
但這並沒有改變任何東西。
Whats the response content-type?:嘗試使用以下方法測試此響應:
也嘗試沒有 dataType: 'json' 並檢查返回!
好吧,我在這個問題上花了一些時間,但我會做一些東西來服務那些有這個問題的人。
錯誤在於想要來自 PHP 的屬性訪問器響應,並引入以下消息:
*SyntaxError: JSON. parse: expected property name or '}'*
你應該做的是轉換 JSON 對此的響應是使用 function JSON.parse (data); 在里面我們傳遞響應變量“數據”。 我將對代碼進行一些注釋以便更好地理解:
success: function (data) {/ / on success ..
var json = JSON.parse (data);/ / Convert the JSON format input
console.log (JSON.parse (data));/ / explore the answer
alert ("" + json.msj);/ / Variable Access Testing with alert
....
在這里一切似乎都很好,但是尺寸存在錯誤,那是因為它執行來自 PHP 的響應的方式。
這是一種正確的實用方法:
我們使用 json_encode function 以 JSON 格式返回數據,在 function 中傳遞了一個帶有所需變量的關聯數組,示例:
echo json_encode (array ('success' => true, 'msg' => 'Hello registered user!'));
在這些變量毫無問題地獲取客戶端之后,簡單地說,這里有一個亞硝酸鹽代碼:
$. ajax ({/ / create an AJAX call ...
data: $ (this). serialize (), / / get the form data
type: $ (this). attr ('method'), / / GET or POST
url: $ (this). attr ('action'), / / the file to call
cache: false,
success: function (data) {/ / on success ..
var json = JSON.parse (data);
$ ('# created'). html (json.msj) / / update the DIV
希望對你有幫助。。。有什么問題可以問。。。
您可以安裝 Firefox 附加組件“JSONView”。 也許這會為您提供有關 JSON 字符串的更多信息。
如果您沒有看到任何內容(特殊的 JSON 標記),您可能會錯過 JSON header。
編輯: Firebug 1.4+ 應根據請求顯示 JSON 選項卡。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.