2011-08-12 177 views
2

我有一個網頁調用時返回該JSON:jQuery的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); 
    } 
}); 

我用螢火蟲來確認正在返回的數據是我放在頂部的。儘管如此,我落入error回調,並第一次看到parsererror在一個警告框,然後我看到

SyntaxError: JSON.parse: expected property name or '}' 

我試圖讓服務回報

{"list":[{"id":"53","desc":"Roberts"}]} 

但這並沒有改變任何東西。

+1

可能重複的[jQuery不會解析我的JSON從AJAX查詢](http://stackoverflow.com/questions/249692/jquery-wont-parse-my-json- from-ajax-query) – sje397

+1

您使用的是哪個版本的jQuery? – andyb

+0

不,@ sje397,這看起來不像那個那個的重複。在這個問題中,JSON顯然是畸形的(沒有引用屬性名稱等)。這個問題中顯示的JSON看起來很好。 – Pointy

回答

3

什麼是響應內容類型?! 嘗試測試這種反應使用這樣的:

Getting the response content-type from jQuery.Post

也儘量不具有數據類型:「JSON」和檢查返回!

+0

內容類型是'text/html'。 – Nik

+0

將response.contentType設置爲「application/json」並查看發生了什麼 –

+0

我刪除了dataType並嘗試在成功函數(我現在可以進入)中手動解析數據,但是我遇到了同樣的問題。它看起來像我的JSON正在獲取HTML編碼。我如何解決這個問題? – Nik

1

您可以安裝Firefox附加組件「JSONView」。也許這會給你更多關於JSON字符串的信息。

如果你沒有看到任何東西(特殊的JSON標記),你可能會錯過一個JSON頭。


編輯: 螢火蟲1.4+應顯示在請求的JSON標籤。

+0

+1:lol「如果你什麼都看不到,你可能會錯過一個JSON頭。」 –

+0

我的意思是分層標記,包括語法高亮。 – 321X

2

好吧,我在這個問題上花了一些時間,但是我會做一些能夠解決這個問題的人。

錯就錯在想一個屬性accesder響應從PHP的到來,推出瞭如下消息:

*SyntaxError: JSON. parse: expected property name or '}'* 

你應該做的是轉換JSON響應,這是使用函數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函數返回JSON格式的數據,內部的功能通過使用是必需的變量的關聯數組,例:

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 

我希望會有所幫助...任何問題隨意問...