jquery美元。使用Django重新发送了ajax POST

时间:2022-10-08 23:44:30

I'm trying to send a simple POST request to a Django view. After the initial POST fails, data is resent as GET. How can I POST successfully?

我试图向Django视图发送一个简单的POST请求。在初始POST失败后,将数据重发为GET。如何成功张贴?

javascript:

javascript:

    data = $('#submit_event').serialize() + '&status=new';

    $.ajax({
        data: data, // get the form data
        type: $('#submt_event').attr('method'), // GET or POST
        url: "/forms/visitor/1/event", // the file to call
        success: function (response) {
            console.log('post was a success')
        }
    })

html:

html:

<form id='submit_event' action="{% url 'forms:event' visitor.id%}" method=
"POST">
{% csrf_token %}

Your Name (event title) <input type="text" name="title" id="title"><br>
    <!-- removed some items for brevity -->
<button type="submit" value="save" name="save" onclick="saveEvent()">Save</button>
<button type="submit" value="delete" name="delete" onclick="deleteEvent()">Delete</button>
</form>

urls.py

urls . py

urlpatterns = patterns('',
# visitor page
url(r'^visitor/(?P<visitor_id>\d+)/$', views.visitor, name='visitor'),

# page to post to
url(r'^visitor/(?P<visitor_id>\d+)/event', views.event, name='event'),
)

views.py:

views.py:

def event(request, visitor_id):
    print 'event page reached'
    print request.POST
    return render_to_response('forms/all_visitor.html')

Traceback:

回溯:

event page reached
<QueryDict: {}>
Internal Server Error: /forms/visitor/1/event
Traceback (most recent call last):
  File "/Users/arcarter/.virtualenvs/base/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/Users/arcarter/code/facsearch/forms/views.py", line 56, in event
    print request.POST['phone']
  File "/Users/arcarter/.virtualenvs/base/lib/python2.7/site-packages/django/utils/datastructures.py", line 295, in __getitem__
    raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
MultiValueDictKeyError: "Key 'phone' not found in <QueryDict: {}>"
[14/Aug/2013 13:31:25] "GET /forms/visitor/1/event?csrfmiddlewaretoken=gHA8G5ngIivsHoVlOw8S8rs3tP1ins1r&title=abc&location=&phone=&detail=&status=new HTTP/1.1" 500 10449
event page reached
<QueryDict: {u'title': [u'abc'], u'detail': [u''], u'phone': [u''], u'location': [u''], u'csrfmiddlewaretoken': [u'gHA8G5ngIivsHoVlOw8S8rs3tP1ins1r'], u'save': [u'save']}>

[14/Aug/2013 13:31:27] "POST /forms/visitor/1/event HTTP/1.1" 200 120

$.ajax calls the success function, after which the server reports an empty . (Data is serialized at this point.) . However, after exiting the $.ajax, the browser re-sends as a GET, which is successful.

美元。ajax调用success函数,之后服务器报告为空。(此时数据被序列化。)但是,退出$之后。浏览器以GET的形式重新发送ajax,这是成功的。

1 个解决方案

#1


1  

It's possible your issue is related to a lack of a CSRF token with your request. Have you defined the following globally to include a CSRF token with all Jquery ajax requests like so...

您的问题可能与您的请求缺少CSRF令牌有关。您是否已经定义了以下全局属性,以包含一个CSRF令牌,其中包含所有Jquery ajax请求,比如……

$.ajaxSetup({ 
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});

#1


1  

It's possible your issue is related to a lack of a CSRF token with your request. Have you defined the following globally to include a CSRF token with all Jquery ajax requests like so...

您的问题可能与您的请求缺少CSRF令牌有关。您是否已经定义了以下全局属性,以包含一个CSRF令牌,其中包含所有Jquery ajax请求,比如……

$.ajaxSetup({ 
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});