我正在尝试在keyup事件上创建一个实时的ajax搜索栏。
当我输入一个字符时,页面会更改网址并重置我的输入文字。当我写更多字符时,如何防止页面刷新?
<script type="text/javascript">
function getSearch(str){
var u = document.getElementById("search").value;
if(str.length == 0){
status.innerHTML = 'field is empty';
}
if(u != "") {
se.onreadystatechange = function(){
if (se.readyState == 4 && se.status == 200){
status.innerHTML = se.responseText;
}
}
}
}
</script>
答案 0 :(得分:0)
您的ajax请求缺少一些配置。您需要告诉请求本身应该调用哪个url,并指定方法。只需更改这些行:
status.innerHTML = 'Verifying...';
//window.location.replace("search.php?search="+str);
// this is why your page reloads. you want to remove this
var se = new XMLHttpRequest();
se.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
se.onreadystatechange = function(){
if (se.readyState == 4 && se.status == 200){
status.innerHTML = se.responseText;
}
}
se.open('POST',"search.php?search="+str);
// you need to open the request, specifying the method and the url
se.send();
这是一个有趣的read on ajax requests