如何将jQuery变量传递给Django视图 [英] how to pass jquery variable to django view

查看:47
本文介绍了如何将jQuery变量传递给Django视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要:我正在创建一个显示用户选择结果的网页.我有两个文件.html和jquery.我创建了一个变量reportsarray = [],当单击完成"按钮时,该变量将收集用户的所有选择.

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.

问题:我必须将report_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.因此它将在不重新加载页面的情况下更改正文的内容.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆