2011-02-26 20 views
2

私はDjangoでWebアプリケーションを開発しました。特定の入力テキストに基づいて画像を更新するために、AJAX呼び出し(jQueryの$.ajax)を呼び出します。次のコードは、目的のために使用されます。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ローダー画像がそのまま残ります。

  • リロードページにdoesnの
  • 実際には、ページを

    • 入力いくつかのテキストと「引く」ボタンをクリックしてください」:私は、次のいずれかを行う場合は今、も起こりませんリロードされます。

      私は今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

    これは、サーバーがデータの送信を完了する前にクライアントが接続を閉じると発生します。

    成功の代わりに関数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']); 
         } 
        }); 
    
    関連する問題