2016-09-21 11 views
0

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"}} 
+0

'$ .getJSON'方法があるので、これはあなたが戻って未定義与えている私は、次のような方法で自分のコードを構造化するだろう非同期。データの要求が行われ、プログラムが応答を待つ間に他のコードの実行をブロックしません。応答が受信された後に実行されるコールバック関数を作成する必要があります。 –

答えて

2

$.getJSONは、非同期操作です。あなたは、あなたが期待しているあなたの目的ではなく、約束を得ています。

は、代わりにこれを試してみてください。

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

dはあなたの応答データが含まれています。

+0

ありがとうございます、新しいhtmlタグで各キーの内容をどのように表示できますか? – user1937021

+0

あなたが構造を知っているかどうか、あるいは動的なものかどうかによって決まります。いくつかのアイデアについては "iterate nested json"を参照できますが、基本的に現在の '$ .each(sales、function'コードは' function(d) 'を' d'に変更するか、その変数を呼びたいと思っているものを変更します。 –

0

Matti Price氏によると、$ .getJSONは非同期です。だから、後に$ .eachをやっても、あなたには何も与えません。 deferred.thenここでjQueryのための

//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); 

チェックアウトドキュメント:https://api.jquery.com/deferred.then/

関連する問題