我在使用POSTed数据而不是使用Django的GET数据时遇到了问题。
这是我简化的urlpatterns类:
urlpatterns = patterns('',
('^hello/$', hello),
('^hello/ajax_info/$', ajax_info),
)
我在views.py文件中有这个视图:
def ajax_info(request):
if request.method == "POST":
print "This is a post"
# do stuff
当你浏览/ hello /中有这个javascript时,网页就会出现:
function loadXMLDoc(name) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
//window.onload()
}
}
// GET method
//parm = values
//xmlhttp.open("GET",name+"?q="+parm, true);
//xmlhttp.send();
// POST method
parms = "data=" + values
xmlhttp.open("POST", "ajax_info", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(parms)
} // end function loadXMLDoc
(在网页中我有一个按钮,当你按下它时会导致调用loadXMLDoc())
如果我取消注释javascript中的“GET方法”,并注释掉“POST方法”,那么我的django视图就会被调用。
但是如果我注释掉“GET方法”并使用“POST方法”代码,那么我的查看器甚至不会被调用。并且django dev服务器返回:
[28/May/2011 00:15:06] "POST /hello/ajax_info HTTP/1.1" 500 69236
我错过了一些明显的东西吗?这些示例似乎表明,即使他们是POST,我的请求也应该发送给我的查看器。
答案 0 :(得分:2)
我不熟悉django,但500
肯定看起来像HTTP状态代码,表明你的回复很糟糕。也许看看JavaScript调试器会发生什么:Firebug,Chrome的工具,Opera Dragonfly等等。
顺便说一句,您可能希望使用类似jQuery的库作为客户端代码。手动ajax是一个巨大的头痛。
答案 1 :(得分:2)
我认为问题是你的view方法没有返回任何内容...尝试访问页面/ hello / ajax_info /并检查一切是否正常工作!
如果是这种情况,您将收到DEBUG = True,此错误: “视图......没有返回HttpResponse对象。”
如果您正在发布某些内容,请确保使用“csrf_token”标记...必须启用Cookie!
答案 2 :(得分:2)
您的问题是您不了解如何在浏览器中调试ajax。
阅读此http://wiki.pylonshq.com/display/pylonscookbook/Debugging+AJAX+requests+using+Firebug,然后使用此技术查找确切崩溃您的ajax视图的内容。
答案 3 :(得分:1)
我记得在某些时候我遇到了一个问题,当我强制url以“/”结束时,POST和ajax无法正常工作。我想尝试删除它是值得的。
urlpatterns = patterns('',
('^hello/$', hello),
('^hello/ajax_info$', ajax_info), # Removed ending slash
)