2013-10-21 60 views
0

Ajax调用后,我试图提取数据的属性 - 第一个元素的消息内容:检索属性从JSON响应

success : function(data) { 

console.log(data[0].message); 
console.log(data); 
console.log(data.message); .....} 


undefined 
[{"message":"Must not "},{"message":"hello"}] 
undefined 

下面的教程http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/我很困惑的是什么,我做错了。虽然最后data.message显然是无效的,但我发现data[0].message没有错......

+4

什么是'typeof(data)'? – lastr2d2

+0

@WayneWang你碰到了......该死的。这是文字。如果我的返回类型不同,我期待错误。 – Aubergine

回答

2

你的数据仍然是int形式的字符串。将var jsonData = JSON.parse(data);加入您的success函数,将其转换为Javascript对象

您没有显示您的AJAX调用,但jQuery的.getJSON()会自动为您解析数据。

-3

我认为你收到字符串,但不是JSON对象 使用eval(数据),该字符串

+1

呃不 - 不要为此使用'eval'。使用'JSON.parse()':它更快更安全。 – 2013-10-21 06:29:02