显示json的内容

时间:2016-09-21 17:58:25

标签: jquery json getjson

我尝试使用undefined从我检索的JSON中显示数据,但以下代码以var sales = $.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }); $.each(sales, function(index, element) { console.log(element[index]) }); 的形式返回。我想在表格的新行中显示所有数据,例如:

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" });

{"9":{"name":"alex lloyd","country":"Germany","antiquity":"new client","amount":"0.0 USD"},"10":{"name" :"asdasdsadasda dasda","country":"Afghanistan","antiquity":"new client","amount":"0.0 USD"},"11":{"name" :"Alex Lloyd","country":"American Samoa","antiquity":"new client","amount":"0.0 USD"},"12":{"name":"alex lloyd","country":"Aruba","antiquity":"new client","amount":"0.0 USD"},"5":{"name":"surgeon bueno","country" :"Spain","antiquity":"renewal","amount":"2686.97 USD"}}

让我回来

.astype()

2 个答案:

答案 0 :(得分:2)

$.getJSON是一个异步操作。你得到了一个承诺,而不是你期望的对象。

试试这个:

 $.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }).then(
     function(d){
        console.log(d);
     });

d将包含您的回复数据。

答案 1 :(得分:0)

正如Matti Price所说,$ .getJSON是异步的。所以在它之后做一个$ .each,不会给你任何东西。我将以类似于以下的方式构造我的代码:

//we call this with themonth(string) as argument to get the promise back
function getSalesInMonth(themonth){
   return $.getJSON(_routes['salesInAMonthJS'], {month: themonth});
}

function renderSalesData(data){

    //here you can do whatever you cant with the data
    $.each(data, function(index, item){
       console.log(item);
    }
}

//in case of error we can show something to the user
function salesDataFail(){
    console.log("Error getting sales data");
}

//to send a request you can do:
getSalesInMonth("September 2016").then(renderSalesData, salesDataFail);

查看jQuery deferred的文档。然后在这里:https://api.jquery.com/deferred.then/