修复实时搜索应用并将其从单个选项转为多个选项

时间:2017-11-28 16:04:41

标签: javascript php multiple-choice livesearch

我今天写了这两个文件,但它还没有工作(应该出现建议结果的窗帘)。我几乎可以肯定它最多只需要很少的修复,但无法解决哪些问题:-( 更多,我完全不知道如何让它允许多种选择。最好的是我点击建议的单词,然后输入逗号和空格作为标记/分隔符,而不是另一个单词来搜索,依此类推。 有什么想法/建议吗?

<!DOCTYPE html>
<html>

<head>
  <script>
    function showResult(str) {
      if (str.length == 0) {
        document.getElementById("livesearch").innerHTML = "";
        document.getElementById("livesearch").style.border = "0px";
        return;
      }

      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        var xmlhttp = new XMLHttpRequest();
      } else { // code for IE6, IE5
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("livesearch").innerHTML = this.responseText;
          document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
        }
      }
      xmlhttp.open("GET", "livesearch.php?q=" + str, true);
      xmlhttp.send();
    }
    }
  </script>
</head>

<body>

  <p><b>Start typing a name in the input field below:</b></p>
  <form>
    <input type="text" size="30" onkeyup="showResult(this.value)">
    <div id="livesearch"></div>
  </form>
</body>

</html>
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL
$q = $_GET["q"];

$hint = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;
?>

1 个答案:

答案 0 :(得分:0)

好吧,伙计们,在我看来,我找到了解决方案。我实际上必须将所有部分放在一起,但理论上它应该可以工作。 有一个图书馆,scriptoculous,它有一个功能(ajax.autocompleter()),它正是我正在寻找的。有关更多参考,请访问:http://www.codicefacile.it/tutorials/tutorials.php/52/Ajax_Autocompleter_nei_nostri_form 我一直在阅读,因为它使用prototype.js作为库来工作,它将与使用jquery.js的同一页面的其他应用程序冲突。但是以下解决方法应该修复它:https://stackoverflow.com/a/3641464/9016436