簡體   English   中英

無法從Ajax響應獲取數據

[英]Can't get data from Ajax response

所以我有這個ajax GET請求到我的API:

$(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> 

您正在獲取集合,您需要對其進行循環

    $.each(JSON.parse(data), function (i, data) {

                var row = data;   // data.comment
                console.log(row);
            });

要么

 $.each(data, function (i, data) {

                var row = data;
                console.log(row);
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM