使用ajax发布表单时StdOut出错

时间:2013-05-11 11:19:20

标签: ajax django

使用以下javascript代码,在发布表单时,我在StdOut中收到错误。

我从网上获得了这个功能。用于发布表格:

$(document).ajaxSend(function(event, 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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

这会从用户处收到点击并发布表单:

$(document).ready(function(){
    $("#idBtSetOnline").click(function(){
        $.ajax({
            type: "POST",
            url: 'command/setOnline',
            data: $("#idFormCommand").serialize(),
            success: function(data)
            {
                if(data == "ok")
                {
                    alert("ok");
                }
                else
                {
                    alert("ko");
                }
            }
        });
    });

HTML表单:

<form name="formCommand" id="idFormCommand" action="command/setOnline" method="post">
    {% csrf_token %}
</form>

Django代码中的接收视图

def command(request, name):
    command = get_object_or_404(Command, name=name)
    execute = Execute(command=command)
    execute.save()
    return HttpResponse("ok")

登录错误(./manage.py runserver):

/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py:808: RuntimeWarning: DateTimeField received a naive datetime (2013-05-11 06:08:19.119291) while time zone support is active.
  RuntimeWarning)
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
    self.finish_response()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
    self.write(data)
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 210, in write
    self.send_headers()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 268, in send_headers
    self.send_preamble()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 192, in send_preamble
    'Date: %s\r\n' % format_date_time(time.time())
  File "/usr/lib/python2.7/socket.py", line 324, in write
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 59697)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 139, in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 704, in finish
    self.wfile.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

我对这个问题一无所知。

执行视图代码(创建对象)。好像返回就是问题..

我前一段时间使用过这种方法,作品就是一种魅力。

读了很多东西

1 个答案:

答案 0 :(得分:0)

如果我将Javascript帖子功能更改为

$("#idBtSetOnline").click(function(){
        $.ajax({
            data: $("#idFormCommand").serialize(),
            type: "post",
            url: "command/setOnline",
            success: function(data) {
                if(data == "ok")
                {
                    alert("ok");
                }
                else
                {
                    alert("ko");
                }
            }
        });
        return false;
    });

它正常工作。 “回归虚假”;声明做了魔术:)

我也删除了

$(document).ajaxSend...

阻止它也有效..