无法从Ajax响应获取数据

无法从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,但我本身需要每个属性

+0

使用JSON.parse(数据); – JYoThI

+0

$ .each方法,遍历数据 –

您的访问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>

+0

是的我已经尝试使用JSON.Parse,但后来我在控制台中得到错误:Uncaught SyntaxError:在位置1的JSON中意外的令牌o – Miko

+0

尝试我更新的答案@Miko – JYoThI

+0

是的,现在工作。谢谢! – Miko

你为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); 
      });