2011-09-05 32 views
1

在我的螢火我看到與服務器響應:爲什麼parseJSON在來自服務器的以下響應中失敗?

{"status":"Results Found","errorcode":"0","result":[{"name":"test","id":"1"},{"name":"some","id":"2"}]} 


When I do the following I get a "o is null" error. 
$.ajax({ 
type: "get", 
url: "http://someurl", 
data: $("#eventsearch").serialize(), 
dataType: 'json', 
success: function(msg){ 
var o = $.parseJSON(msg); //o is NULL error 
} 

然而,當我做的parseURL在同一個字符串,但不能作爲服務器響應一切都很好。這裏發生了什麼?

var t = '{"status":"Results Found","errorcode":"0","result":[{"name":"test","id":"1"},{"name":"some","id":"2"}]}'; 

var o = $.parseJSON(t); //everything is good here 

回答

4

當您將dataType:json的JSON是已經被解析你不必做

var o = $.parseJSON(msg);

你可以做

console.log(msg.result[0].name); 
1

呼叫如果指定dataType: 'json'到jQuery的ajax函數msg已經是一個對象,通過解析從服務器返回的JSON數據創建。 jQuery將解析響應的工作。

0

var o = $.parseJSON(msg); //o is NULL error 

在語法上不能夠產生錯誤。即使parseJSON要返回null,將該空值分配給新變量(然後您立即忽略)並不是錯誤。

您是不是顯示所有相關的代碼?

在ajax操作完成之前,您是否嘗試使用o,也就是說,沒有等到成功回調被調用?

1
console.log(msg.result[0].id); // gives u 1 
console.log(msg.result[1].id); // gives u 2 
相關問題