简体   繁体   English

Javascript到Django views.py?

[英]Javascript to Django views.py?

This may sound simple, but how do I send the data from a Javascript array in my index.html template to my views.py? 这可能听起来很简单,但如何将我的index.html模板中的Javascript数组中的数据发送到我的views.py?

When the user clicks a "Recommend" button, my code calls a function that accesses my database and prints a name on the template. 当用户单击“推荐”按钮时,我的代码调用一个访问我的数据库并在模板上打印名称的函数。

def index(request):
    if(request.GET.get('Recommend')):
        sql_handler.recFunc()
        context['name'] = sql_handler.name
        return render(request, 'polls/index.html', context)

I have an array of checkbox values in Javascript that are calculated after the user presses "Recommend". 我在Javascript中有一个复选框值数组,这些值是在用户按下“推荐”后计算的。 I want to send it to my index view and use it as the parameter for another function. 我想将它发送到我的索引视图并将其用作另一个函数的参数。

So: 所以:

def index(request):
    if(request.GET.get('Recommend')):
        sql_handler.recommend()
        context['name'] = sql_handler.name
        //something??
        tags = check_array_javascript
        context['tags'] = tags
        return render(request, 'polls/index.html', context)

How can I do this? 我怎样才能做到这一点? I've been searching similar questions, but I'm new to Django and web development in general, so I either did not understand the answers or they didn't help me. 我一直在寻找类似的问题,但我是Django和Web开发的新手,所以我要么不理解答案,要么他们没有帮助我。

Alright, so for sending data from the client (JavaScript) to the backend (your Django app) you need to employ something called Ajax, it stands for Asynchronous JavaScript and XML. 好吧,因此,为了从客户端(JavaScript)向后端(您的Django应用程序)发送数据,您需要使用名为Ajax的东西,它代表异步JavaScript和XML。 Basically what it does is allowing you to communicate with your backend services without the need of having to reload the page, which, you would have to do using a normal POST or PUT form submission. 基本上它的功能是允许您与后端服务进行通信,而无需重新加载页面,您必须使用普通的POST或PUT表单提交。

The easiest implementation is using jQuery . 最简单的实现是使用jQuery jQuery is first and foremost a DOM manipulation library but since its inception has grown to encompass much more than that. jQuery首先是一个DOM操作库,但自从它开始以来已经发展到包含更多的东西。

A jQuery ajax call looks like this. jQuery ajax调用看起来像这样。

$(document).ready(function() {
    $.ajax({
        method: 'POST',
        url: '/path/to/your/view/',
        data: {'yourJavaScriptArrayKey': yourJavaScriptArray},
        success: function (data) {
             //this gets called when server returns an OK response
             alert("it worked!");
        },
        error: function (data) {
             alert("it didnt work");
        }
    });
});

This can then be checked for in your views.py 然后可以在views.py检查它

def index(request):
    if request.is_ajax():
        #do something
        request_data = request.POST
        return HttpResponse("OK")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM