Django开发服务器没有从Ajax请求中提供错误

时间:2009-12-22 09:28:10

标签: ajax django debugging

我一直试图在我的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");
    };

的Python:

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 个答案:

答案 0 :(得分:2)

在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错误。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

这可能是因为服务器返回错误代码(500)并且你的jQuery cod在错误时没有做任何事情。你可以发布你正在使用的$ .get或$ .post代码吗?

编辑:如果您使用$ .load,则可以创建一个回调函数,以便显示错误。这很简单,你需要定义一个类似于这个的函数:

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

这样您就会将错误消息放入整个文档并查看它。我不确切知道,如果上述工作,因为我无法测试它,但你应该能够构建一些有关此事的工作。

答案 3 :(得分:0)

如果使用$ .ajax,则会出现错误回调设置,实现起来非常简单:

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