2

我想复制选定的实时搜索并通过 ajax 填充文本框名称“oki”。就像谷歌实时搜索一样。

我正在从 xml 文件中检索数据到 ajax 实时搜索。

这是我的search.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
    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("livesearch").innerHTML=xmlhttp.responseText;

      document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
  xmlhttp.open("GET","livesearch.php?q="+str,true);
  xmlhttp.send();
}

</script>

</head>
<body>

<form>
<p id="demo"></p>
<input name="oki" type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

我的livesearch.php:

<?php

$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$y=$xmlDoc->getElementsByTagName('country');

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

//lookup all links from the xml file if length of q>0
if (strlen($q)>0) {
  $hint="";
  for($i=0; $i<($y->length); $i++) {


    if ($y->item($i)->nodeType==1) {
      //find a link matching the search text
if (strpos(strtolower($y->item($i)->nodeValue), strtolower($q)) === 0) {

if ($hint=="") {$hint="<a  onclick='alert()'>" . $y->item($i)->nodeValue . "</a>";
        } else {
          $hint=$hint . "<br />".
          $y->item($i)->nodeValue;
        }
      }
    }
  }
}





// Set output to "no suggestion" if no hint was found
// or to the correct values
if ($hint=="") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>

我的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<link>
<countries>
  <country code="AF" iso="4">Afghanistan</country>
  <country code="AL" iso="8">Albania</country>
  <country code="DZ" iso="12">Algeria</country>
  <country code="AS" iso="16">American Samoa</country>
  <country code="AD" iso="20">Andorra</country>
  <country code="AO" iso="24">Angola</country>
  <country code="AI" iso="660">Anguilla</country>
  <country code="AQ" iso="10">Antarctica</country>
  <country code="AG" iso="28">Antigua And Barbuda</country>
  <country code="AR" iso="32">Argentina</country>
  <country code="AM" iso="51">Armenia</country>
  <country code="AW" iso="533">Aruba</country>
  <country code="AU" iso="36">Australia</country>
  <country code="AT" iso="40">Austria</country>
  <country code="AZ" iso="31">Azerbaijan</country>
  <country code="BS" iso="44">Bahamas</country>
  <country code="BH" iso="48">Bahrain</country>
  <country code="BD" iso="50">Bangladesh</country>
</countries>

 </link>

注释 我尝试使用单击时的锚点但未成功

4

1 回答 1

0

你试过select2吗?看起来它具有您正在寻找的功能。 https://select2.github.io/

于 2015-10-28T02:59:48.663 回答