Get POST data in django form AJAX from

前端 未结 5 557
甜味超标
甜味超标 2021-01-15 19:28

I\'m going to get parameter form AJAX request in Django, Here\'s what I\'m doing:

base.html:

{% csrf_tok
相关标签:
5条回答
  • 2021-01-15 19:50

    What's happening is that you haven't prevented the browser's default submit action from taking place. So your Ajax POST is done, but then immediately the browser itself POSTs - and, as Michal points out, your form doesn't include a name field, so the lookup fails.

    You need to do two things to fix this. Firstly, use e.preventDefault(); in your JS click method. Secondly, check for request.is_ajax() at the top of your view.

    0 讨论(0)
  • 2021-01-15 19:59

    Instead of using a click handler, you could setup a more robust form submit function to do the same thing. Returning false cancels the default submit behavior.

    $("form").submit(function() {
        $.post("/", {
            name: "MY TEXT",
        });
    
        return false;
    });
    
    0 讨论(0)
  • 2021-01-15 20:01

    Prevent the form from submitting with "e.preventDefault()". Also, it's probably better to bind to the form just in-case the user hits Enter instead of clicking:

    base.html

    <form method="POST" id="register">{% csrf_token %}
    First name: <input type="text">
    <input type="submit" value="Register">
    </form>
    

    main.js

    $(document).ready(function(){
        $("#register").live("submit", function(e){
            $.post("/", {
                name: "MY TEXT",
            });
            e.preventDefault();
        });
    });
    
    0 讨论(0)
  • 2021-01-15 20:05

    I guess the problem is that you don't have named the text input within html:

    <input type="text" name="name">
    
    0 讨论(0)
  • 2021-01-15 20:11

    I think it should be

    $.post("../save_note/", {
            data:'name=MY TEXT'
        });
    

    And

    if 'name' in request.POST:
    
    0 讨论(0)
提交回复
热议问题