我的想法是,我有这个选择框,当我输入输入文本时,它会使用给定的通配符搜索数据库中的给定公司。
HTML
<span id='errorCompany'></span>
<input type='text' name='search_query_bedrijf' id='search_query_bedrijf' onkeypress='checkForm(\"query_bedrijf\")' placeholder='Search companies'>
<select id='bedrijf' name='bedrijf'>
PHP code is inside here to get all the data from the database
</select>
的Javascript
function checkForm(type){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("bedrijf").innerHTML = xmlhttp.responseText;
}
}
var wildcard = document.getElementById("search_query_bedrijf").value;
xmlhttp.open("GET","getBedrijven.php?wildcard=" + wildcard,true);
xmlhttp.send();
if(document.getElementById("bedrijf").options[0].value == "NoData"){
document.getElementById("errorCompany").innerHTML = "Not a valid company.";
}else{
document.getElementById("errorCompany").innerHTML = "";
}
}
AJAX
<?php
include("include/connect.php");
$wildcard = $_GET["wildcard"];
if($wildcard == ""){
$sqlSelectWildcardLeverancier = "SELECT * FROM companies";
}else{
$sqlSelectWildcardLeverancier = "SELECT * FROM companies WHERE company LIKE '%".$wildcard."%'";
}
if(!$res = $mysqli->query($sqlSelectWildcardLeverancier)){
trigger_error('Fout bij query: '.$mysqli->error);
}else{
while($row = $res->fetch_assoc()){
$companyID = $row["companyID"];
echo "<option value='$companyID'>".$row['company']."</option>";
}
}
$number_bedrijven = $res->num_rows;
if($number_bedrijven == 0){
echo "<option value='NoData' selected>No data found for this query</option>";
}
?>
现在这一切都像我应该的那样(它从通配符中获取数据等) 当我输入像WallmartQ&#39;这样的内容时,它会给我“此查询没有找到数据&#34;”但我必须输入另一封信&#39; WallmartQE&#39;所以它给了我跨度的错误信息 下面是一个gif来更好地解释它:http://i.imgur.com/0W0hWUB.gif
答案 0 :(得分:0)
只需将options[0].value == "NoData"
支票放入异步回调中 - 否则会在响应到达之前执行,并且会在&#34; old&#34;数据。有关详细信息,请参阅How do I return the response from an asynchronous call?。
function checkForm(type) {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("bedrijf").innerHTML = xmlhttp.responseText;
if (document.getElementById("bedrijf").options[0].value == "NoData") {
document.getElementById("errorCompany").innerHTML = "Not a valid company.";
} else {
document.getElementById("errorCompany").innerHTML = "";
}
}
}
var wildcard = document.getElementById("search_query_bedrijf").value;
xmlhttp.open("GET", "getBedrijven.php?wildcard=" + wildcard, true);
xmlhttp.send();
}