我是ajax的新手,并使用Django进行Web开发。 现在我的模板包含:sample.html
<html>
<body>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "/showtime/", true);
ajaxRequest.send(null);
}
</script>
<form name='myForm'>
Name: <input type='text' onBlur="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
在views.py中我的功能是:
def showtime(request):
string = "Ajax Application"
data = {"string" : string}
pprint (data)
return render_to_response("sample.html",data)
现在,输出不符合预期。模板不会收到服务器发送的响应 代码有什么问题?
答案 0 :(得分:4)
如果您尝试使用AJAX返回的字符串填充文本字段,则不应使用render_to_response
。只需返回字符串。
def showtime(request):
s = "Ajax Application"
print "Returning %s"%s #is this line executed?
return HttpResponse(s, mimetype="text/plain")
答案 1 :(得分:0)