简体   繁体   中英

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. 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. I want redirect page and print a result there.

html code:

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

javascript code:

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

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

view in 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. You can see here some answers on how to redirect the page from 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 requests are useful if you want to do some async http requests to the server without refreshing (or redirecting) the page. So I would say, don't use an Ajax request here, just simply submit the form. You can have a look for example here to see how forms work in javascript. You can also check this Django tutorial about using forms. 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. It can be a bit confusing at the beginning, but I think it is worth spending some time understanding Django forms.

I do something like this, it work, but I dont know is it correct.

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

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

js function

$(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

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

calc.html

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

Page redirect to calc/ and show correct not none matrix. Result

What you get when using window.location.href = "127.0.0.1:8000/calc" is normal. You are just redirecting to the same page without any url query parameters.

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.

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. You can still use some Django tempting en return some rendered HTML that you will then add dynamically with some Javascript code.

It could be something like that:

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

<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. See this tutorial for example.

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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