[英]Is it possible to pass Ajax response as template context variable in Django?
我向服務器發送了一個 Ajax 請求以獲取一些過濾數據,這是我從服務器收到的示例:
(3) [{…}, {…}, {…}]
0: {id: 1, title: "12 Rue Longueil", slug: "12-rue-longueil", latitude: null, longitude: null, …}
1: {id: 2, title: "15 Rue Sherbrooke LM", slug: "15-rue-sherbrooke-lm", latitude: null, longitude: null, …}
2: {id: 3, title: "Cycle Neron", slug: "cycle-neron", latitude: "-73.5987000000000000", longitude: "45.4799000000000000", …}
length: 3
__proto__: Array(0)
以上數據是從控制台記錄的。
我想在下面卡片中的 HTMl 標簽中顯示這些數據。
但為此,我需要使用接收到的數據並使用 JavaScript 例如document.createElement('DIV')
創建子級。 然后放置這些數據。
$(document).on('submit', "#filterform", function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: "{% url 'listing:search' %}",
data: {
listing_for: $('#listing_for').val(),
// cutted
},
success: function (response) {
const listings = eval(response);
const content = document.getElementById('content');
for (let i = 0; i < listings.length; i++) {
const div = document.createElement('div');
div.className = 'listing mgb-1';
div.innerHTML = data[i].title;
content.appendChild(div);
// have to create, add lots of divs and classes
}
}
})
})
我想知道是否有辦法將 Ajax 請求數據作為模板變量發送? 還是我必須使用 Javascript 對所有 HTML 標簽進行硬編碼?
編輯:根據第一個答案編輯內容,創建一個單獨的 HTML。
def search(request):
...
lst = list()
for listing in queryset:
ser = ListingSerializer(listing)
lst.append(ser.data)
return render(request, 'listing/newHtmlFile.html', {'listings': json.dumps(lst)})
單獨的 HTML:
{% for list in listings %}
<div class="jumbotron">
<h1>{{ list.title }}</h1>
</div>
{% endfor %}
和 ajax 請求:
success: function (response) {
document.querySelector('#content').insertAdjacentHTML('beforeend', response);
}
是的你可以。 基本上,這個想法是制作一個單獨的 HTML 文件,該文件將由處理 AJAX 請求的視圖呈現。 然后,您可以使用 JavaScript 和insertAdjacentHTML()
function 將其插入原始 HTML 文件中。
看看這個例子:
看法:
def ajax_handler(request):
# ... logic
return render(request, 'newHtmlFile.html', {'your_context': data})
原裝HTML文件
<div id='container'>
</div>
newHtmlFile.html
<p>{{ your_context }}</p>
JavaScript 部分(在這個例子中我使用香草,而不是 JQuery )
let ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if (this.readyState === 4){
if (this.status === 200){
document.querySelector('#container').insertAdjacentHTML('beforeend', this.responseText);
}
}
}
ajax.open('GET', '/ajax-handler-url', true);
ajax.send();
如果您有興趣了解它是如何工作的,我們可以將其分解如下:
render()
方法並將該數據作為上下文數據傳遞給模板render()
方法的實際作用是(讓我在這里多余)渲染一個 HTML 文件(將 HTML 本身與您傳遞的上下文數據相結合)並返回一個HTTPResponse
object 包含一個渲染的 text.$.ajax()
function。insertAdjacentHTML()
function 到 append 將文本呈現到所需元素(在上面的示例中, #container
div)。一種快速且可能“骯臟”的方法是使用 javascript 中的反引號字符串:
success: function (r) {
const listings = JSON.parse(r); // with the correct headers from django, this should't be needed.
listings.forEach(e => $('#content').append(`
<div class="listing mgb-1">${e.title}</div>
`));
}
您應該使用適當的標題從 django 返回您的數據,以便您自動獲得 json 並且不需要eval(response)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.