我正在尝试创建一个与我的数据库通信的动态AJAX搜索栏。这是我的代码。
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
var search = getXmlHttpRequestObject();
function ajaxSearch(){
if (search.readyState == 4 || search.readyState == 0){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", 'searchSuggest.php?search=' + str, true);
search.onreadystatechange.handleSearchSuggest;
search.send(null);
}
}
function handleSearchSuggest(){
if(search.readyState == 4){
var ss = document.getElementById('ajaxSearch');
ss.innerHTML = '';
var str = search.responseText.split("\n");
for(i=0; i<str.length-1; i++){
var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
suggestion += 'onmouseout="javascript.suggestOut(this);"';
suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
suggestion += 'class="suggestLink">' + str[i] + '<div>';
ss.innerHTML += suggestion;
}
}
}
function suggestOver(divValue){
divValue.className = "suggestLink";
}
function suggestOut(divValue){
divValue.className = "suggestLink";
}
function setSearch(x){
document.getElementById('searchBox').value = x;
document.getElementById('ajaxSearch').innerHTML = '';
}
问题是readyState从0变为1,但随后它不会变为任何其他状态。我需要将其更改为4以进入函数 handleSearchSuggest()。 我也在控制台中收到此错误: TypeError:search.onreadystatechange为null
答案 0 :(得分:1)
您需要正确设置回调功能。
search.onreadystatechange = handleSearchSuggest;
请注意,就绪状态为1表示OPENED
,4表示DONE
。您可以通过XMLHttpRequest
类的属性进行测试:
XMLHttpRequest.UNSENT == 0
XMLHttpRequest.OPENED == 1
XMLHttpRequest.HEADERS_RECEIVED == 2
XMLHttpRequest.LOADING == 3
XMLHttpRequest.DONE == 4
答案 1 :(得分:0)
尝试:
search.onreadystatechange = handleSearchSuggest;