如何将 jquery 变量传递给 Django 视图 [英] how to pass jquery variable to django view
问题描述
总结:我正在创建一个显示用户选择结果的网页.我有两个文件.html 和 jquery.我创建了一个变量 reports_array = [ ],它在单击完成"按钮时收集用户的所有选择.
Summary: I am creating a web page which shows the results of user selections. I have two files. html and jquery. I have created a variable reports_array = [ ] which collects all the selections of user when "Done" button is clicked.
问题:我必须将reports_array[] 值传递给django 视图.
Issue: I have to pass reports_array[ ] values to the django view.
这是jquery的代码
Here is the code for jquery
.on('click','.done', function(){
var report_array = [];
report_array.push(
{
Layer_Table: layer_array,
Benefits_Table: benefits_array,
Map_Layer_selection: save_selection_layer,
Map_Benefits_selection: save_selection_benefits,
});
console.log(report_array);
这是view.py的代码
Here is the code for view.py
def done(request):
template = loader.get_template('maps/done.html')
context = RequestContext(request, {
'reports_link': report_array, //I believe this is not correct.
})
return HttpResponse(template.render(context))
如何将 jquery 中的 report_array 传递到这个上下文"...????假设 done.html 包含以下代码
how to pass report_array from jquery to this "context"...???? assume done.html contains following code
<head>
<title>Reports</title>
</head>
<body>
<p>{{ reports_link }}</p>
</body>
我是 Django 界面的新手.假设 url.py 是正确的.我正在寻找我在这里缺少的逻辑.
I am new to django interface. Assume url.py is correct. I am looking for logic that i am missing here.
提前致谢
推荐答案
我不确定我是否理解您想要如何呈现报表数组.但是要将 JQuery 数组传递给 Django 视图,您可以使用 AJAX 调用 Django URL
I am not sure I understood how you want to present the report array. But to pass JQuery array to Django view you can use AJAX call to Django URL
var obj = {'report_array': report_array}
$.ajax({
type: 'POST',
url: '/DESTINATION_URL/',
contentType: 'application/json; charset=utf-8', //EDITED
data: JSON.stringify(obj),
success: function(data) {
$('body').html(data); //EDITED
},
error: function(rs, e) {
alert(rs.responseText);
}
});
然后在您的 views.py 中
Then in your views.py
import json
from django.template.loader import render_to_string
def done(request):
params = json.loads(request.body)
report_array = params['report_array']
html_data = render_to_string('maps/done.html', {'reports_link': report_array})
return HttpResponse(html_data)
那么你的 done.html 可以是这样的:
Then your done.html can just be this:
<body>
<p>{{ reports_link }}</p>
</body>
这样 AJAX 将渲染您的页面以在成功时显示 report_array.所以它会在不重新加载页面的情况下改变body的内容.
This way AJAX will render your page to show the report_array on success. So it will change the content of body without reloading the page.
这篇关于如何将 jquery 变量传递给 Django 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!