当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - django recognize request.method="POST" as "GET"

问题描述:

I saw a lot of similar question but no-one had resolved.

I've got ajax request:

 <script type="text/javascript">

$('#activeform').on('submit', function(event){

event.preventDefault();

var _self = $(this);

var token = $('input[name="csrfmiddlewaretoken"]').val();

alert( _self.serialize()) // sanity check

$.ajax({

type: _self.attr('method'),

url: _self.attr('action'),

data: _self.serialize(),

contentType: "application/x-www-form-urlencoded;charset=utf-8",

headers: {"X-CSRFToken": token},

beforeSend: function(xhr) {

xhr.setRequestHeader("Accept-Charset","utf-8");

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");},

success: function(json) {

alert("Send!")},

error: function( xhr, textStatus ) {

alert( [ xhr.status, textStatus ] )},

complete: function() {

alert("Complete")},

crossDomain: false

});

return

}); </script>

This one perfomed successfully, and i got success and complete msgs.

Browser also recognize POST request, when submit. But my django view

request.method == 'POST' return False. Anyone have suggestions?

网友答案:

I had a long way to make registration with ajax. So code below make the deal.

<body>
<div class='large-3 large-offset-3 columns'>
    <form method='POST' id="activeform" >
    {% csrf_token %}
    {{form}}
    {% if error %}
    <p><h6>{{error}}</h6></p>
    {% endif %}
    <input type='button' class='button' value='Зарегистрироваться' onclick="submit_by_id()"> 
    </form>
</div>


<script type="text/javascript">
    function submit_by_id()  {
        alert('Перед аджаксом');
        var token = $('input[name="csrfmiddlewaretoken"]').val();
                $.ajax({
            method: "POST",
            url: "/auth/registrate/",
            data: $('#activeform').serialize(),
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            dataType:"html",
                    success: function(data, textStatus, jqXHR) {
                        //код в этом блоке выполняется при успешной отправке сообщения
                        alert("Успех" + data + 'Serialized string ' + $('#activeform').serialize())},
                    error: function( xhr, textStatus ) {
                    alert( [ xhr.status, textStatus ] )},
                complete: function() {
                        //код в этом блоке выполняется при успешной отправке сообщения
                        alert("Комплит")},
            headers: {"X-CSRFToken": token, "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"},
            crossDomain: false

        });
    }
</script>

</body>
分享给朋友:
您可能感兴趣的文章:
随机阅读: