从 ajax jQuery 中的数据变量中获取属性

get property from data variable in ajax jQuery

本文关键字:变量 获取 属性 数据 ajax jQuery      更新时间:2023-09-26

我尝试获取响应对象(data变量)中的变量值。这是我在整个data console.log得到的:

 {"comment_id":7,"view": ......

但是当我尝试这样做来获得comment_id时,我得到了undefined

console.log(data['comment_id']); // undefined
console.log(data.comment_id); // undefined

我做错了什么?

您必须解析在 JSON 对象中收到的 JSON 字符串。

参见 $.parseJSON(如果你有 jQuery)

否则在纯 JS 中

var mjsn = JSON.parse( your_json );
console.log(mjsn['key']);
// or 
console.log(mjsn.key);

如果它来自 ajax 请求,您的内容类型应该是 application/json 以使该代码正常工作

如果没有解析它

var json = JSON.parse(data);
console.log(json.comment_id);