Javascript到Django views.py? [英] Javascript to Django views.py?

查看:90
本文介绍了Javascript到Django views.py?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来很简单,但如何将我的index.html模板中的Javascript数组中的数据发送到我的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?

当用户点击推荐按钮时,我的代码会调用一个访问我的数据库并在模板上打印名称的函数。

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)

我在Javascript中有一组复选框值,这些值是在用户按下推荐后计算的。我想将它发送到我的索引视图并将其用作另一个函数的参数。

I have an array of checkbox values in Javascript that are calculated after the user presses "Recommend". I want to send it to my index view and use it as the parameter for another function.

所以:

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)

我该怎么做?我一直在寻找类似的问题,但我是Django和Web开发的新手,所以我要么不理解答案,要么他们没有帮助我。

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.

推荐答案

好吧,因此,为了将数据从客户端(JavaScript)发送到后端(您的Django应用程序),您需要使用名为Ajax的东西,它代表异步JavaScript和XML。
基本上它的功能是允许您与后端服务进行通信,而无需重新加载页面,使用普通的POST或PUT表单提交,您将不得不这样做。

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. 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.

最简单的实现是使用 jQuery 。 jQuery首先是一个DOM操作库,但自从它开始以来已经发展到不止于此。

The easiest implementation is using jQuery. jQuery is first and foremost a DOM manipulation library but since its inception has grown to encompass much more than that.

A jQuery ajax call 看起来像这样。

$(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");
        }
    });
});

然后可以在 views.py

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

这篇关于Javascript到Django views.py?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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