2017-09-02 75 views
1

我使用Django的模板用於顯示數據,在模板我打電話這樣的Ajax請求:如何在Django模板中顯示ajax響應(json類型)的數據?

{% for entry in entries %} 

<script> 
var ids = {{ entry }}; 
$.ajax({ 
    ....... 
    ....... 
    success: function (data) { 
     alert(JSON.stringify(data)); 
     } 
}); 
{% endfor %} 

有像在JSON甲酸數據:

[{"model":"main.mymodel","pk":258160,"fields":{"idn":920087058,"name":null,"ico":null,"street":"PO BOX 149","city":"HYDER","state":"AK","zip":"99923"}}] 

我想顯示如表(在同一模板中)

  • IDN-920087058

  • 名空

  • 街道PO BOX 149
    ...

+0

爲什麼你用這個Ajax,而不是直接從視圖中傳遞數據到模板? –

+0

實際上,我有多個數據(ids)在同一次點擊,我認爲從數據庫獲取數據作爲ajax請求與該ids –

+0

嘗試此JSON.parse(結果) –

回答

0

試試這個:

<table> 
    <thead> 
     <tr>idn</tr> 
     <tr>name</tr> 
     <tr>street</tr> 
    </thead> 
    <tbody id="myTable"></tbody> 
</table> 

<script> 
var = TableItem = "" 

{% for entry in entries %} 
var ids = {{ entry }}; 
$.ajax({ 
    ....... 
    ....... 
    success: function (data) { 
     $.each(data, function(index, value){ 
      TableItem +='<tr>' + 
           '<td>'+value.fields.idn+'</td>' + 
           '<td>'+value.fields.name+'</td>' + 
           '<td>'+value.fields.street+'</td>' + 
          '</tr>' 
      $('#myTable').html(TableContent); 
     }) 
     } 
}); 

{% endfor %} 

我覺得一個ajax查詢會更好。

ids = [{% for entry in entries %}{{ entry.id }}{% if forloop.last %}{% else %},{% endif %}{% endfor %}]