Django - Ajax表单在发送数据时失败

时间:2012-11-26 14:08:47

标签: django jquery

我正在尝试设置表单按钮以保存表单而不重新加载页面。

一切看起来都很正确;但我想我错过了一些东西。这是我的代码:

ajax部分:

$('#submit').click(function() {

        var title = $('#id_title').val();
        var body = $('#id_body').val();
        var isdraft = $('#id_isdraft').is(':checked');

        var ajaxOptions = {
            type: 'post',
            url: '/admin/post/save/',
            data: {
                'title': title,
                'body': body,
                'isdraft': isdraft
            },
            success: function(){
                alert("save success");
             },
            error: function(){
                alert("fail");
             }
           };

        $.ajax(ajaxOptions);
});

观看部分

@require_POST
def save_post(request):
     title = request.POST['title']
     body = request.POST['body']
     isdraft = request.POST['isdraft']
     owner = request.user 

     post = Post(title=title, body=body, isdraft=isdraft, owner=owner)
     post.save()

     return HttpResponse(200)

网址:

url(r'^admin/post/save/', view='save_post', name='save_post'),

当我点击提交按钮时; ajax错误函数叫。

谢谢

编辑:

on firefox;它将数据保存到db中。它会显示错误但会再次保存。

但在控制台[runserver lines];有一个错误:

Exception happened during processing of request from ('10.10.10.1', 42526)
Traceback (most recent call last):
  File "/usr/lib/python2.6/SocketServer.py", line 560, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 322, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/opt/sosyate_/sosyate_env/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 139, in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "/usr/lib/python2.6/SocketServer.py", line 618, in __init__
    self.finish()
  File "/usr/lib/python2.6/SocketServer.py", line 661, in finish
    self.wfile.flush()
  File "/usr/lib/python2.6/socket.py", line 297, in flush
    self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 32] Broken pipe

但是在铬;没有像这样的错误。它只是抛出我在ajax函数下定义的错误。

1 个答案:

答案 0 :(得分:0)

我发现装饰器与ajax请求不兼容。我建议删除它并将检查放在方法

def save_post(request):
    if request.method == 'POST':
         title = request.POST['title']
         body = request.POST['body']
         isdraft = request.POST['isdraft']
         owner = request.user 

         post = Post(title=title, body=body, isdraft=isdraft, owner=owner)
         post.save()

         return HttpResponse(200)