简体   繁体   English

如何将参数从javascript传递到django视图?

[英]How to pass arguments from javascript to django view?

I'm trying to do page with simple calculator. 我正在尝试用简单的计算器做页面。 I made calculator in js, and now, when I click button I want to pass arguments from js to django. 我在js中制作了计算器,现在,当我点击按钮时,我想将参数从js传递到django。 Count them there and print on redirect page. 在那里计算它们并在重定向页面上打印。

I have problem with redirect page. 我有重定向页面的问题。 When I dont put button in form, js script call calc view, but dont redirect page. 当我没有把按钮放在窗体中时,js脚本调用calc视图,但是不要重定向页面。 I want redirect page and print a result there. 我想重定向页面并在那里打印结果。

html code: HTML代码:

<form action="calc/" method="post">
    {% csrf_token %}
    <input id='btn' type="submit" value="CALC" onclick="change()">
</form>

javascript code: javascript代码:

function change(){
    var foo = 1;
    var foo1 = [1, "tralal", true, ''];

    $.ajax({

        url: 'calc/',
        data : {
            'foo': foo,
            'foo1': foo1,
        },
        success: function (data) {
            alert("it worked!");
        }
    }
)};

urls in django django的网址

path('calc/', views.calc, name='calc')

view in django 在django中查看

def calc(request):
    foo = request.GET.get('foo')
    print(foo)
    foo1 = request.GET.getlist('foo1[]')
    print(foo1)
    context = {'data': foo1}
    return render(request, 'calc.html', context)

If you want to redirect to another page, you have to do it explicitly from the javascript when the success callback is called. 如果要重定向到另一个页面,则必须在调用成功回调时从javascript中显式执行此操作。 You can see here some answers on how to redirect the page from javascript. 你可以在这里看到一些关于如何从javascript重定向页面的答案。 To do so, you will have to have another view for serving the result page. 为此,您必须有另一个视图来提供结果页面。 The results of the calculation can be kept in the server (cached), or communicated from the client. 计算结果可以保存在服务器中(缓存),也可以从客户端传送。

But, I wonder why you are using an Ajax request for that. 但是,我想知道你为什么要使用Ajax请求。 Ajax requests are useful if you want to do some async http requests to the server without refreshing (or redirecting) the page. 如果要在不刷新(或重定向)页面的情况下对服务器执行某些异步http请求,则Ajax请求非常有用。 So I would say, don't use an Ajax request here, just simply submit the form. 所以我想说,不要在这里使用Ajax请求,只需提交表单即可。 You can have a look for example here to see how forms work in javascript. 您可以在这里查看示例以了解表单在javascript中的工作方式。 You can also check this Django tutorial about using forms. 您还可以查看有关使用表单的Django教程 Django has some tools for handling forms that can be quite convenient when for instance you want to update or create new instances in your database model. Django有一些处理表单的工具,例如你想在数据库模型中更新或创建新实例时非常方便。 It can be a bit confusing at the beginning, but I think it is worth spending some time understanding Django forms. 它在开始时可能有点令人困惑,但我认为值得花一些时间来理解Django表单。

I do something like this, it work, but I dont know is it correct. 我这样做,它有效,但我不知道它是否正确。

views.py views.py

def link(request):
    global matrix
    matrix = request.GET.getlist('foo1[]')
    return HttpResponseRedirect('/calc/')


def calc(request):
    if request.is_ajax:
        global matrix
        context = {'data': matrix}
        return render(request, 'calc.html', context)
    else:
        return HttpResponseRedirect('/')

urls.py urls.py

path('link/', views.link, name='link'),
path('calc/', views.calc, name='calc'),

js function js功能

$(document).ready(function() {
$("#btn").click(function(e) {
    var foo = 1;
    var foo1 = [1, "tralal", true, ''];

    $.ajax({
        url: 'link/',
        data : {
            'foo': foo,
            'foo1': foo1,
        },
        success: function (data) {
             window.location.href = "calc/"
        }
    });
});
});

html code HTML代码

<input id='btn' type="submit" value="COUNT">

calc.html calc.html

{% for d in data %}
    <p>"{{ d }}"</p>
{% endfor %}

Page redirect to calc/ and show correct not none matrix. 页面重定向到calc /并显示正确的not none矩阵。 Result 结果

What you get when using window.location.href = "127.0.0.1:8000/calc" is normal. 使用window.location.href =“127.0.0.1:8000/calc”时得到的结果是正常的。 You are just redirecting to the same page without any url query parameters. 您只是重定向到同一页面而没有任何url查询参数。

So, you basically want to redirect to the same page? 那么,您基本上想要重定向到同一页面? Why then do you want to redirect? 为什么然后要重定向? This does not make much sense to me. 这对我来说没什么意义。 And again, if you wanna redirect, don't use AJAX, and follow the "normal" approach for submitting forms. 再次,如果您想重定向,请不要使用AJAX,并按照“正常”方法提交表单。

So what I think makes more sense, is to not redirect, but use the data you receive from the the AJAX request and show the information. 所以我认为更有意义的是,不重定向,而是使用从AJAX请求收到的数据并显示信息。 You can still use some Django tempting en return some rendered HTML that you will then add dynamically with some Javascript code. 您仍然可以使用一些Django诱惑返回一些呈现的HTML,然后您将使用一些Javascript代码动态添加。

It could be something like that: 它可能是这样的:

Javascript 使用Javascript

$.ajax({
    url: 'link/',
    data : {
        'foo': foo,
        'foo1': foo1,
    },
    success: function (data) {
         $('#result-container').html(data)  // add the data in the div container
         $("#your-form").trigger('reset'); //you should reset your form
    }
});

Main HTML at "/" should contain “/”中的主要HTML应包含

<div id="result-container"></div>

And you should just get rid of your link view and have the other somehow like that 你应该摆脱你的链接视图,让其他人像这样

def calc(request):
    if request.is_ajax:
        matrix = request.GET.getlist('foo1[]')
        context = {'data': matrix}
        return render(request, 'calc.html', context)

But I tell you again, you should use Django forms for what you are doing. 但我再次告诉你,你应该使用Django表格来做你正在做的事情。 See this tutorial for example. 例如,请参阅本教程

I hope it helps. 我希望它有所帮助。

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

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