我是 JavaScript 新手,一直在使用 PHP、Ajax、Javascript 和 mysql 进行实时搜索。
它适用于第一个 ID 字段,但我总共需要使用 8 个输入字段,我尝试编辑 getElementById 但搜索不起作用。
我应该如何编辑 JavaScript 以允许在 8 个输入字段中的每一个上使用实时搜索,并且仍然将所选搜索项作为字段值提供?
JavaScript:
function liveSearch()
{
var url = "livesearch.php";
var s = document.getElementById('med1').value;
var params = "&s="+s;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status != 200) {
document.getElementById('searchResults1').innerHTML='<li>Loading...</li>';
}
if(http.readyState == 4 && http.status == 200) {
document.getElementById('searchResults1').innerHTML = http.responseText;
}
}
http.send(params);
}
function sendToSearch(str){
document.getElementById('med1').value = str;
document.getElementById('searchResults1').innerHTML = "";
}
PHP:
$s = $_REQUEST["s"];
$output = "";
$s = str_replace(" ", "%", $s);
$query = "SELECT * FROM drug_list WHERE NAME LIKE '%" . $s . "%' or COMMON_NAME LIKE '%" . $s."%' or ALIAS LIKE '%" . $s . "%' LIMIT 10";
$squery = mysql_query($query);
if((mysql_num_rows($squery) != 0) && ($s != "")){
while($sLookup = mysql_fetch_array($squery)){
$displayName = $sLookup["COMMON_NAME"];
$product_name = $sLookup['NAME'];
$dose = $sLookup["DOSAGE"];
$units = $sLookup["UNITS"];
$output .= '<li onclick="sendToSearch(\''.$product_name.' (' . $displayName .') '.$dose.' '.$units. '\')">'.$product_name.' (' . $displayName .') '.$dose.' '.$units.'</li>';
}
}
echo $output;
HTML 表格(部分 - 使用 ID='med(n)' 的 8 种药物):
<td size='20'>Medication 1</td><td><input type='text' name='med1' id='med1' size='40' title='i.e.-Metoprolol 50 mg twice a day' onkeyup='liveSearch()' /></td><td size='40'><input type='text' name='med1_reason' size='40' title='i.e.-Highblood Pressure' /></td>
</tr>
<tr><td colspan='3' align='left'><span style='color:blue; cursor:pointer'><ul id="searchResults1"></ul></span></td></tr>
<tr>
<td size='20'>Medication 2</td><td><input type='text' name='med2' id='med2' size='40' title='i.e.-Metoprolol 50 mg twice a day' onkeyup='liveSearch()' /></td><td size='40'><input type='text' name='med2_reason' size='40' title='i.e.-Highblood Pressure' /></td>
</tr>
<tr><td colspan='3' align='left'><span style='color:blue; cursor:pointer'><ul id="searchResults2"></ul></span></td></tr>
<tr>