【发布时间】:2019-01-03 20:05:03
【问题描述】:
我正在使用 Ajax+Jquery 从 PHP api 获取数据。在我最后一步的那个 PHP api 中-
$data_enc = json_encode($data); 回声 $data_enc;
我得到了这个返回-
{"headers":["Age","Count","Consent","Intent"],"data":{"17":{"Age":"17","Count":2,"Consent":"2","Intent":0},"18":{"Age":"108","Count":3,"Consent":"3","Intent":0},"115":{"Age":"115","Count":1,"Consent":"1","Intent":0},"117":{"Age":"117","Count":2,"Consent":"2","Intent":0},"118":{"Age":"118","Count":1,"Consent":"1","Intent":0},"Totals":{"Age":"Total","Count":67,"Consent":67,"Intent":0}}}
在 Jquery 方面,
success: function(data){
alert(typeof(data)); //returns string
},
当我在 jQuery Ajax 成功中执行 typeof(data) 时,它说它是一个字符串。 我需要在表格中显示这些数据,其中列有 Age、Count、Consent、Intent。
我尝试在 jQuery 端循环对象,但无法获得所需的结果。
【问题讨论】:
-
你在 ajax 调用中使用
dataType: "json",吗? -
使用
JSON.parse()解析JSON! JSON 没有数据类型。 -
“它说它是一个字符串”,“我尝试循环遍历对象”。字符串!=对象。你的第一个谷歌应该是“如何将 json 转换为对象?”
-
@VincentDecaux 我使用了它,但它出错了,这让我再次想到 Taplar 所说的,我得到的是一个字符串而不是一个对象。但是不会做一个 json_encode 使它成为一个 JSON 对象吗?
-
@manishk 你想使用 JSON.parse(jsonData) 函数 -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript php jquery ajax