我正在尝试使用 python 创建 AJAX 实时搜索(例如 Google Suggest)。我是 AJAX 新手,所以我开始阅读一些教程和其他有用的文档。我找到了一个例子,http://www.w3schools.com/ajax/ajax_aspphp.asp ,这基本上是我想要完成的,但这个例子仅适用于 asp/php。到目前为止,我设法对程序的 python 部分进行了编码,但是我遇到了一个未定义的错误。
下面是我的 javascript 代码(test.js,与示例中的代码基本相同):
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","search.py?q="+str,true);
xmlhttp.send();
}
在 firefox 4 中,出现错误“str is undefined”。
下面是我的 python 代码的 html 部分:
<html>
<head>
<title>Live Search</title>
<script src="http://localhost:8000/test.js" type="text/javascript"></script>
</head>
<body>
<h1> Cities </h1>
Enter Anything: <input type="text" id="sname" onkeyup="showHint(this.text)">
%(search)s
</body>
</html>
注意:在我有 onkeyup="showHint(this.id) 之前,但由于某种原因它不起作用..它一直将“sname”作为查询传递,而不是我在输入字段中键入的内容。
请帮忙
最佳答案
<input>
元素没有属性文本。这就是为什么 this.text
及以后str
未定义。也许<input type="text" id="sname" onkeyup="showHint(this.value)">
会做你想做的事。
关于javascript - Python/Javascript/AJAX 实时搜索帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009149/