2009-12-22 147 views
0

我一直在尝试让一些Ajax的东西在我的Django应用程序中工作,但它一直很困难,因为由于某些原因语法和类型错误不会导致服务器崩溃,并且默默地失败。这怎么可能?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)) 
+0

如何发送Ajax请求的JavaScript代码样子?如何接受Ajax请求的Python代码看起来像?你能否更新它并将其发布在你的问题中。 – 2009-12-22 09:40:36

+0

如果您尝试调试ajax的JavaScript端,请尝试:http://getfirebug.com/ – miku 2009-12-22 09:40:53

+0

我添加了代码:-) – SapphireSun 2009-12-22 09:48:24

回答

1

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

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

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

这样你就会把错误信息到整个文档,看看它。我不完全知道,如果上述工作,因为我无法测试它,但你应该能够构建一些工作。

+0

我是jQuery的新手 - 我该怎么做? – SapphireSun 2009-12-22 10:51:11

+1

您必须使用$ .ajax,$ .get,$ .post。你可以发布吗? – gruszczy 2009-12-22 11:31:52

+0

嗯,我设法通过直接访问URL来获取错误页面,但无论如何,我使用的是这个页面定义的$ .load:http://docs.jquery.com/Ajax/load#urldatacallback我相信它是使用$ .get,因为我传递它没有参数。我如何看到它的输出?我尝试使用alert(div.load(...));但我只是得到了[object object]或其他的东西。 谢谢你的帮助! – SapphireSun 2009-12-22 19:26:36

1

你在哪里寻找错误报告?它显然不会出现在主网页中,因为您尚未请求整页刷新。调试Ajax的最好方法是通过Firebug,您可以在Console选项卡中查看 - 每个Ajax请求都会显示一行,如果发生错误,则会显示一行。然后,您可以展开该行以查看完整的响应,即可以在新选项卡中打开的好Django回溯。

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错误上弹出。

0

如果使用$就存在错误回调的设置,这是为了实现很简单:

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