我有一个包含文本字段和按钮的表单.当我开始输入时,它会显示来自我的数据库的提示,点击按钮或点击回车键会显示搜索结果.AJAX用于提示和搜索结果,并且运行良好.
问题是它只在页面加载后第一次工作.如果我想要其他搜索,则不会回复.它只显示以前的搜索结果,直到刷新页面,但该showhint()功能运行良好.
<input type="text" id="txt" onkeyup="showhint(this.value)"/>
<input type="button" value="search" onclick="searchresult()"/>
Run Code Online (Sandbox Code Playgroud)
AJAX功能:
function searchresult() {
var key = document.getElementById("txt").value;
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mid").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","keyprocess.php?q=" + key, true);
xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)
问题是什么?
我猜测它第一次或刷新时的工作原因是因为事件处理程序不是在ajax请求之间持久化.我会研究jQuery,因为它有助于缓解这样的问题.
对于jquery <version 1.7 .delegate()方法执行以下操作
根据一组特定的根元素,为现在或将来与选择器匹配的所有元素的一个或多个事件附加处理程序.
1.7后你应该使用.on()方法.
基本上,如果页面上的元素从ajax请求更改,则.delegate()或.on()方法仍将允许处理事件.
更新:
//This needs to be within the $(document).ready function
//Attach an event handler to the ID called txt that fires on changes
$("body").on("change", "#txt", function(event){
//get the value from the input
var $val = $(this).val();
//Send the $val to keyprocess.php via ajax call
//Output Results
});
Run Code Online (Sandbox Code Playgroud)