从响应中获取json值
{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
如果我提醒响应数据,我看到上述内容,如何访问id
值?从响应中获取json值
我控制器返回这样的:
return Json(
new {
id = indicationBase.ID
}
);
在我的AJAX的成功我有这样的:
success: function(data) {
var id = data.id.toString();
}
它说data.id
是undefined
。
如果响应是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
这是Json.parse()...谢谢! – slandau 2011-04-11 17:38:28
请注意,这可能无法在旧版浏览器上运行。你可以使用[json2.js](https://github.com/douglascrockford/JSON-js)来解决这个问题。 – lonesomeday 2011-04-11 17:47:05
通常情况下,你可以通过它的属性名称访问它:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
或许你有一个需要变成对象的JSON字符串:
var foo = jQuery.parseJSON(data);
alert(foo.id);
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results
现在是一个对象。
使用safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);
如果响应是JSON那么这将是这样的:
alert(response.id);
否则
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
你是如何接收数据?你能展示一些Javascript吗? – lonesomeday 2011-04-11 17:34:26
'response.id'我认为:) – 2011-04-11 17:34:35