简体   繁体   中英

Django: can I have both “action=” and jQuery assigned to the same form?

I have a form inside my template, which sends the submitted data to "{% url 'javascript:index' %}" :

<form id="login-form" action="{% url 'javascript:index' %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input id="create_table" type="submit" value="View results" />
</form>

But I have also a jQuery script assisgned to the same form like this:

$('#login-form').on('submit', function(event){
    event.preventDefault();
    console.log("form submitted!");  // sanity check
    $('#table').load('http://127.0.0.1:8000/results',function(){
    $('#go_back').remove();
    }); 
});

Problem is, the form is never posted to "{% url 'javascript:index' %}" , because the jQuery script is executed first.

Is there any way to make the form submission happen in this order: first send the data to "{% url 'javascript:index' %}" , then run the script?

You should be using AJAX to do this.

$('#login-form').on('submit', function(event){

    event.preventDefault();

    var myform = document.getElementById('login-form');
    var fd = new FormData(myform );

    var post_url = $(this).find('#login-url').val();

    var csrftoken = getCookie('csrftoken');
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $.ajax({
        url : post_url,
        data : fd,
        cache: false,
        processData: false,
        contentType: false,
        type : "POST",
        success : function(data) {
            console.log("form submitted!");  // sanity check
            $('#table').load('http://127.0.0.1:8000/results',function(){
                $('#go_back').remove();
            }); // <-- Add it Here!
        },
        error : function() {
            console.log("something bad happened")
        }
    });

});

I haven't got a clue what your code does but I have included it in the success call as a demonstration. No idea if it will work.

Note1: don't put the URL in 'action' if you are using AJAX. It does not matter technically but it is a good habbit not to code things in a way you do not intend them to work. Instead add the url as a hidden input to your form which you can then grab during the JQuery/AJAX call, ie

<input type="hidden" id="login-url" value="{% url 'javascript:index' %}" />

Note2: you can return data from your view using

return JsonResponse({'hello': 'world'})

which you can then access in the success call via data.hello, which will return 'world'.

Note3: FormData is supported by most browser right now though I am not entirely sure about some off the older versions of Internet Explorer.

Either way you can always POST data via a standard dictionary. Simply define a dictionary like

fd = {variable_name: variable_value}

and remove

cache: false,
processData: false,
contentType: false,

from the AJAX call.

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