我已檢查此stackoverflow topic,但此snippet不適用於我。我有一個錯誤:'Template'對象沒有屬性'nodelist'。 我的數據不顯示在模板中。我的目標是刷新已經呈現的頁面的數據,以便從模板更新單個塊。 我的代碼如下:django - 使用間隔期AJAX調用刷新模板中的JSON數據
views.py:
def my_view(request):
if request.is_ajax():
my_data = MyObject.objects.all()
ctx = { 'test': my_data.values()}
return render(request, "temp.html", context=ctx)
我可以在Chrome中看到控制檯我的JSON數據提交AJAX請求後,但這個數據沒有在模板中顯示。
我的模板:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
{% for v in test %}
{{ v.path }}
{% endfor %}
<script>
window.setInterval(function(){
$(document).ready(function() {
$.ajax({
async: true,
type: "GET",
url: "/requests/",
});
});
}, 2000);
</script>
我在Chrome中看到控制檯v.path數據。
的json數據結構如下:
[
{
"pk":4233,
"model":"hello.webrequest",
"fields":{
"method":"GET",
"meta":"",
"user":null,
"is_secure":false,
"raw_post":"",
"user_agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36",
"host":"127.0.0.1:8765",
"path":"/requests/",
"cookies":"{\"sessionid\": \"1t0ect4zsnfdh5ght7kqhmf3soezueg1\", \"csrftoken\": \"yLImX79fUFJD7kpGQCcfBZawwFtOUcFR\"}",
"remote_addr_fwd":null,
"status_code":200,
"time":"2015-12-17T15:38:04.242Z",
"post":null,
"remote_addr":"127.0.0.1",
"get":null,
"uri":"http://127.0.0.1:8765/requests/",
"is_ajax":false
}
}
]
而且,我已經試過的HttpResponse,但它不爲我工作太
能否請您提供一些100 %工作示例?
在本主題Render JSON objects through Django template-tag我找到了這樣的建議:
if the json comes from your own application, you could return an html fragment instead of json.
但我不太明白我怎麼能做到這一點。
更新:我解決了我的問題。我拒絕使用django模板標籤。相反,我只是將JSON傳遞給jQuery腳本並生成所需的html。
可以共享'了'數據,看看它是如何的樣子,如果有任何錯誤信息顯示? – DhiaTN
將JSON添加到我的問題 –
'{%for v in test%}'僅在列表中有效,但數據不在列表中,表明它不工作,它應該如下[{...},{ ...}] – DhiaTN