2011-04-11 143 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"}';