代码之家  ›  专栏  ›  技术社区  ›  SapphireSun

Django Development Server不提供来自Ajax请求的错误

  •  0
  • SapphireSun  · 技术社区  · 16 年前

    我一直在尝试在我的Django应用程序中使用一些Ajax工具,但这很困难,因为出于某种原因,语法和类型错误不会导致服务器崩溃,并且正在悄无声息地失败。怎么会这样?

    javascript(jquery):

     add_foo = function() {
       var numfoos = $("div#foos_container > div.foo").length + 1;
       var foo_id = numfoos + "-foo";
       var div = $("<div></div>").attr("id",foo_id).addClass("foo");
       div.load("http://localhost:8000/ajax/get/url/");
       div.appendTo("div#foos_container");
        };
    

    蟒蛇:

    def ajax_add_foo(request):     
      print request.session['editing_foos'].keys()
      keys = request.session['editing_foos'].keys()
      if len(keys) == 0:
        next_key = 1
      else:
        next_key = max([ id_from_prefix(key) for key in keys ])
      print next_key
    
      form = FooForm(prefix=next_key)
      print next_key
      request.session['editing_foos'].update( {create_prefix(FooForm, next_key) : -1 } ) # This foo is new and has no pkey
      print request.session['editing_foos']
      return render_to_response( 'bar/foo_fragment.html',
            {'fooform' : fooform, },
            context_instance=RequestContext(request))
    
    4 回复  |  直到 10 年前
        1
  •  1
  •   gruszczy    16 年前

    这可能是因为服务器返回错误代码(500),而您的jquery代码不会对错误做任何处理。你能发布你正在使用的.get或.post代码吗?

    编辑: 如果您使用的是$.Load,那么有一个回调函数的位置,您可以创建它来显示错误。很简单,您需要定义一个类似于此的函数:

    function (responseText, textStatus, XMLHttpRequest){
        if (textStatus < 200 || textStatus >= 299){
            $(document).html(responseText);
        }
    }
    

    这样,您将把错误消息放入整个文档中并看到它。我不知道,如果上面的工作,因为我不能测试它,但你应该能够构建一些工作在这上面。

        2
  •  2
  •   Zulu    10 年前

    在Ajax错误中,Django仍然会生成完整的“调试屏幕”,但不会自动显示。

    为jquery ajax错误注册一个全局处理程序,在新窗口中打开“responsetext”: (将此代码放入“onready”中)

    $(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
        // open the Django Debug screen in a new window: 
        var w = window.open('','','');
        w.document.write(XMLHttpRequest.responseText);          
    });
    

    这会导致熟悉的Django“调试”页面在Ajax错误时弹出。

        3
  •  1
  •   Daniel Roseman    16 年前

    您在哪里查找错误报告?很明显,它不会出现在主页上,因为您没有请求刷新整个页面。调试Ajax的最佳方法是通过Firebug,在控制台选项卡中可以看到每个Ajax请求都有一行,如果发生错误,该行将变为红色。然后您可以展开该行以查看完整的响应,即漂亮的Django回溯,您也可以在新的选项卡中打开它。

        4
  •  0
  •   Jeff Wu    15 年前

    如果您使用$.Ajax,则有一个错误回调设置,这很容易实现:

    $.ajax({
      ...
      error: function(XMLHttpRequest, textStatus, errorThrown){
        document.write(XMLHttpRequest.responseText);
      },
      ...
    });