gpt4 book ai didi

javascript - 无法使用 Python 和 Django 进行 AJAX 调用

转载 作者:行者123 更新时间:2023-11-30 13:38:01 25 4
gpt4 key购买 nike

我仍在学习使用 javascript 和 django,昨天我尝试做一个简单的 hello world 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>

我的观点.py

from django.http import HttpResponse

def test(request):
response_string="hello"
return HttpResponse(response_string,mimetype='text/plain')

我的网址.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)),
)

更新

下面是代码

alt text

最佳答案

我刚刚测试了你的代码。当我单击“单击我”按钮时,确实向 test View 发出了请求。我能够证实这一点。但是,与您所说的不同, View 返回HttpResponse。要自己验证这一点,请使用网络浏览器访问 http://localhost:8000/test/ url。走着瞧吧。

乍一看,您的问题似乎与 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!="") 的计算结果为 true(null!= "",因此)并删除 div 的内容。

关于javascript - 无法使用 Python 和 Django 进行 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3783839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com