gpt4 book ai didi

javascript - 使用 javascript 刷新 django 子模板 - 仅重新加载页面的一部分

转载 作者:行者123 更新时间:2023-12-01 23:22:13 31 4
gpt4 key购买 nike

我正在尝试通过使用 js 调用 View 来刷新子模板。似乎什么都没有发生,尽管服务器受到攻击并且似乎返回了响应。

目标是刷新包含的部分而不刷新整个页面。

最小的例子:

views.py

def ajax_view(request):
context = {}
context['data'] = 'data'
return render(request, "test.html", context)// <-- reaches here, but no rendering

test.html

{{data}}

main.html

<script type="text/javascript">

function getQuery() {
var request = new XMLHttpRequest(),
method = 'GET',
url = '/ajax/';

request.open(method, url);
request.send();
}
</script>

{% include "test.html" %} // <-- does not update

最佳答案

在 friend 的帮助下,我解决了这个问题。

我将详细回答我的问题,因为我 100% 确定稍后需要有人弄清楚如何执行此操作。很高兴为您省去麻烦。

我不得不改变我对它如何运作的心智模型。

我仍然使用 javascript 向服务器发送请求, View 返回模板化的 HTML。

但是,这是重要的部分,我所做的是获取呈现的 HTML(从响应中返回的内容 return render(response, "your_template.html", context))并用该 HTML 替换我页面的那部分。

这是 Javascript。

function getQuery(item) {
// Sends a request to the API endpoint to fetch data

let request = new XMLHttpRequest();
let method = 'GET';
let query = // omitted

let url = '/ajax/?' + query;
request.open(method, url);
request.onload = function () {
// the response is the rendered HTML
// which django sends as return render(response, "your_template.html", context)
let myHTML = request.response;
// This is the important part
// Set that HTML to the new, templated HTML returned by the server
document.getElementById('flex-container-A').innerHTML = myHTML;
};
request.send();
}

为了完整起见,这里是 View :views.py

def ajax_view(request):
"""
Server API endpoint for fetching data
"""

context = {}
queryset = Form.objects

if request.method == 'GET':
query = request.GET.get('q')

# do some stuff and get some data

context['data'] = data

return render(request, "my_template.html", context)

希望对您有所帮助!这是一种常见的模式,但并不经常如此明确地提及。

关于javascript - 使用 javascript 刷新 django 子模板 - 仅重新加载页面的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67930375/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com