在进行AJAX调用时Django异常

时间:2011-02-26 18:47:54

标签: ajax django

我用Django开发了一个网络应用程序。它使用AJAX调用(使用jQuery的$.ajax)来基于某些输入文本更新图像。以下代码用于此目的:

$('img#diagram').attr('src', '/images/ajax/ajax_loader.gif');
$.ajax({
    type:       'POST',
    url:        '/draw/',
    data:       { 'diagram':  $('#diagram-text').val() },
    cache:      false,
    success:    function(mesg, txtStatus, XmlHttpRequest) {
        result = $.parseJSON(mesg);
        if (result['error']) {
            alert('An error was encountered: ' + result['error']);
        }
        else {
            $('img#diagram').attr('src', result['diagram_url']);
        }
    },
    error:      function(XmlHttpRequet, txtStatus, errorThrown) {
        alert('Failed to draw the diagram!\n' + errorThrown);
    },
    dataType:   'html'
});

它工作正常,即在更改输入并单击“绘图”按钮后更新图像。

问题是,如果我没有输入任何内容,并单击“绘图”按钮,AJAX加载程序图像仍然存在。现在,如果我执行以下任一操作, nothing 就会发生:

  • 输入一些文字并点击“绘图”按钮
  • 重新加载页面

事实上,页面没有重新加载。

如果我现在停止Django开发服务器,我会收到以下错误:

Exception happened during processing of request from ('127.0.0.1', 44166)
Unhandled exception in thread started by <function inner_run at 0x9f6d5dc>
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 48, in apport_excepthook
    if not enabled():
TypeError: 'NoneType' object is not callable

Original exception was:
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/commands/runserver.py", line 60, in inner_run
    run(addr, int(port), handler)
  File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 721, in run
    httpd.serve_forever()
  File "/usr/lib/python2.6/SocketServer.py", line 226, in serve_forever
    self._handle_request_noblock()
  File "/usr/lib/python2.6/SocketServer.py", line 283, in _handle_request_noblock
    self.handle_error(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 335, in handle_error
    import traceback
ImportError: No module named traceback

有人可以提出任何建议吗?当然我可以进行验证以防止空字符串。但是为什么这个实际发生了,因为AJAX是异步的?

1 个答案:

答案 0 :(得分:1)

当客户端在服务器完成数据发送之前关闭连接时会发生这种情况。

尝试使用函数done而不是成功。

   $.ajax({
        url: "/draw/",
        type: "POST",
        data: { 'diagram':  $('#diagram-text').val() },
    }).done(function(data) {
        result = $.parseJSON(mesg);
        if (result['error']) {
          alert('An error was encountered: ' + result['error']);
        }
        else {
            $('img#diagram').attr('src', result['diagram_url']);
        }
    });
相关问题