2009-12-22 149 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); 
    }, 
    ... 
});