2011-04-11 103 views
9
{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"} 

如果我提醒響應數據,我看到上述內容,如何訪問id值?從響應中獲取json值

我控制器返回這樣的:

return Json(
    new { 
     id = indicationBase.ID 
    } 
); 

在我的AJAX的成功我有這樣的:

success: function(data) { 
    var id = data.id.toString(); 
} 

它說data.idundefined

+2

你是如何接收數據?你能展示一些Javascript嗎? – lonesomeday 2011-04-11 17:34:26

+0

'response.id'我認爲:) – 2011-04-11 17:34:35

回答

22

如果響應是json而不是字符串,那麼

alert(response.id); 
or 
alert(response['id']); 

否則

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}'); 
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301 
+1

這是Json.parse()...謝謝! – slandau 2011-04-11 17:38:28

+1

請注意,這可能無法在舊版瀏覽器上運行。你可以使用[json2.js](https://github.com/douglascrockford/JSON-js)來解決這個問題。 – lonesomeday 2011-04-11 17:47:05

3

通常情況下,你可以通過它的屬性名稱訪問它:

var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}; 
alert(foo.id); 

或許你有一個需要變成對象的JSON字符串:

var foo = jQuery.parseJSON(data); 
alert(foo.id); 

http://api.jquery.com/jQuery.parseJSON/

+0

說undefined。 – slandau 2011-04-11 17:34:13

+0

張貼了最高。謝謝 – slandau 2011-04-11 17:37:09

1
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"} 
console.log(results.id) 
=>2231f87c-a62c-4c2c-8f5d-b76d11942301 

results現在是一個對象。

0

如果響應是JSON那麼這將是這樣的:

alert(response.id); 

否則

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';