无法使用Python和Django进行AJAX调用
我还在学习JavaScript和Django,昨天我尝试做一个简单的“你好,世界”的AJAX练习。
服务器的日志显示,Python代码确实被调用了,但当我在Firebug中查看xmlhttp.responseText和responseXML时,Django/Python似乎没有返回任何东西。
更新:我去掉了对返回的HTTP状态的检查,这样代码就直接打印服务器的输出了。
<html>
<head>
<title>Javascript example 1</title>
<script type="text/javascript">
function doAjax()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
alert("response text: "+xmlhttp.responseText+"\n"
+"response XML: "+ xmlhttp.responseXML);
if (xmlhttp.responseText!="") {
$("thediv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://127.0.0.1/test/",true);
xmlhttp.send();
}
function $(element){
return document.getElementById(element);
}
</script>
</head>
<body>
<input type="button" value="click me" onClick=javascript:doAjax()>
<br/><br/>
<div id="thediv">
some test
</div>
</body>
</html>
我的views.py
from django.http import HttpResponse
def test(request):
response_string="hello"
return HttpResponse(response_string,mimetype='text/plain')
我的urls.py
from django.conf.urls.defaults import *
from project1.views import test
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^test/$', test)
# Example:
# (r'^project1/', include('project1.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
更新
这是代码运行的效果
2 个回答
我刚刚测试了你的代码。当我点击“点击我”按钮时,确实向 test
视图发送了请求。我确认了这一点。不过,和你说的不一样,这个视图确实返回了 HttpResponse
。你可以自己验证一下,打开你的网页浏览器,访问 http://localhost:8000/test/
,看看会发生什么。
乍一看,你的问题似乎和JavaScript有关。我不太清楚具体哪里出错了,但我会尝试调试一下JS代码,看看情况。
更新
我确认错误确实出在你使用的JavaScript上。我发现了两个错误。首先:
if (xmlhttp.readyState==4 && xmlhttp.status==0)
难道 status
不应该是 200
吗?所以我把它改成了:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
更新 2
我发现我漏掉了 $
函数。
问题在于有两个 if
条件。第一个条件为真时,div的内容确实更新为“hello”。但是第二个 if (xmlhttp.responseXML!="")
也 为真(null
是 != ""
,所以),这就把div的内容清空了。
学习的时候用原生的JavaScript是很好的,但随着你水平的提高,肯定要用一些框架,比如jQuery
或者Prototype
。框架可以让你的代码更简洁,开发速度更快,还能帮你解决不同浏览器之间的兼容性问题。
如果你用jQuery,你的代码可能会像这样:
<html>
<head>
<title>Javascript example 1</title>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
<script type="text/javascript">
function doAjax()
{
$.ajax({
url: 'http://localhost:8000/test/',
success: function(data) {
$('#thediv').html(data); //jQuery equivalent of document.getElementById('thediv').innerHTML = data
}
});
}
</script>
</head>
<body>
<input type="button" value="click me" onClick="javascript:doAjax()"/>
<br/><br/>
<div id="thediv">
some test
</div>
</body>
</html>
因为jQuery自带一个默认的$()
函数,所以如果你使用这个框架,就不需要在代码里自己定义这个函数了。
虽然这个回答有点偏题,但我希望对你有帮助。