无法从Ajax响应获取数据
问题描述:
所以我有这个AJAX GET请求我的API:无法从Ajax响应获取数据
$(document).ready(function() {
//id=$("#id").val();
url="api.php/fcomment/"+5;
$.ajax({
type: "GET",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
console.log(data);
alert(data);
$('.greeting-content').append(data.comment);
}
});
});
我得到的JSON数据,它的结果是:
[{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}]
我会喜欢从JSON格式中获取值,但没有添加到div。如果我添加JSON.stringify围绕数据然后我得到整个JSON,但我本身需要每个属性
答
您的访问data.comment
这是不确定的访问这样data[0].comment
$('.greeting-content').append(data[0].comment);
您可以使用$.each
来获取所有数据
data = [{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}];
console.log(data[0].comment);
$.each(data,function(i,v){
console.log(data[i].comment);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答
你为G ETTING收集你需要遍历它
$.each(JSON.parse(data), function (i, data) {
var row = data; // data.comment
console.log(row);
});
OR
$.each(data, function (i, data) {
var row = data;
console.log(row);
});
使用JSON.parse(数据); – JYoThI
$ .each方法,遍历数据 –