2017-05-24 140 views
0

所以我有這個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方法,遍歷數據 –

回答

0

您的訪問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

0

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