我的网站上有一个搜索框,用于搜索书籍数据库。向用户显示以下选项:
- 搜索查询(文本输入字段)
- 在哪里搜索(带有选项的选择字段:当前、存档或全部)
- 要搜索的内容(带有选项的选择字段:标题、作者、所有者或读者)
当用户在搜索字段中输入输入内容时,会弹出下面的书名建议,就像您搜索时谷歌一样。我想知道如何检查他们选择搜索的选项(即标题、作者等)并相应地显示建议。
我使用的当前代码如下:
HTML
<form method='get' action='/main'>
<label for='search'>Search</label>
<div style='position:relative;display:inline;'>
<input type='text' id='search' name='search' onkeyup='showHint(this.value)' autocomplete='off'/>
<div style='display:inline;' id='txtHint'></div>
</div>
<select name='searchIn'>
<option name='searchIn' id='searchIn' value='current' selected>Current</option>
<option name='searchIn' id='searchIn' value='archive'>Archive</option>
<option name='searchIn' id='searchIn' value='all'>All</option>
</select>
<select name='searchBy' onChange='getSearchBy(this.value)'>
<option name='searchBy' id='searchBy' value='Title' selected>By Title</option>
<option name='searchBy' id='searchBy' value='Author'>By Author</option>
<option name='searchBy' id='searchBy' value='Owner'>By Owner</option>
<option name='searchBy' id='searchBy' value='Reader'>By Reader</option>
</select>
<input type='submit' class='submit' value='Submit'/>
</form>
AJAX/Javascript
function getSearchBy(val){
return val;
}
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;
}
}
var searchBy = getSearchBy(document.getElementById('searchBy').value);
xmlhttp.open('GET','get_hint.php?q='+str+'&searchBy='+searchBy,true);
xmlhttp.send();
}
文件“get_hint.php”完成所有处理和查询数据库,并将结果作为 txtHint 元素的 innerHTML 返回...
选择“作者”选项后,getSearchBy 函数似乎没有返回“作者”,有什么想法吗?
更新
我知道其中许多答案可能是正确的,但我将最快到达的答案标记为正确的。感谢大家的快速回复!