javascript - Python/Javascript/AJAX 实时搜索帮助

标签 javascript python ajax

我正在尝试使用 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/

相关文章:

python - 函数内局部变量的生命周期(内存范围)

python - Pandas 数据框分组求和

javascript - 当 Asnyc 设置为 true 时,XMLHttpRequest 不起作用

jquery - ajax在rails中加载图像

javascript - 修改后的变量不会显示

javascript - 递归在 Chrome/Firefox 中工作,但在 IE7 中不工作

javascript - 为子实例创建同名属性,而父属性的可写为假

python - Django - 来自模板标签内变量的字符串

javascript - jQuery UI token

php - 用文本填充空格