使用Ajax XML自动完成


Autocomplete with Ajax XML

我想自动完成我的输入字段。所有的数据都是从我的数据库中提取的,并用我的autocomplete.php文件处理——它运行良好,并将所有匹配的列存储在一个XML文件中,该文件将发送回服务器。Onkeyup i GET将q="键入的字符串"发送到自动完成。

当从服务器接收到XML文件时,我在处理该文件时遇到了问题。我的计划是将所有匹配的结果附加到我的数据列表中,它将作为自动完成
这是我的代码:

<input id="showCustomerId" name="customer" type="text" min="1" max="100" list="customerlist" required>
<datalist id="customerlist"></datalist>

脚本:

$("#showCustomerId").on('keyup', function(){
                var str = document.getElementById('showCustomerId').value;
                var xmlhttp;
                if (str.length===0) {
                    document.getElementById("customerlist").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) {
                        var docroot= xmlhttp.responseXML.documentElement;
                        var customers = docroot.getElementsByTagName('customer');
                        for(var i=0; i<customers.length; i=i++){
                            var option = customers[i].firstChild.nodeValue;
                            $("#customerlist").append("<option value='"" +option+ "'">");
                        }
                    }
                }
                xmlhttp.open("GET","ini/search-customers.php?q="+str,true);
                xmlhttp.send();
            });

autocomplete.php

$q=$_GET['q'];
$result = // do query;
$xml = new SimpleXMLElement('<xml/>');
while($row = mysqli_fetch_assoc($result)){
    $xml->addChild("customer",$row['customer_id']);
}
header('Content-type:text/xml');
print($xml->asXML());

现在我的问题不是获取值,当我在xml处理程序函数中提醒结果时,我得到了正确的值,但当我像这里那样执行代码时,我的网站会冻结!我得到了这些值,但我就是不能以正确的方式将它们附加到我的数据列表中?

我想构建自动完成最简单的方法是通过jQuery自动完成或Twitter Typehead。因此,简单的jquery更适合这种情况。在head中添加jQuery最新版本未测试代码。

$(document).ready(function(){
//Assuming #customerlist is the ID of the text box which you need to see autocomplete
//No need to get value also - by default
$("#customerlist").autoComplete({source:"ini/search-customers.php"});
// Same time autocomplete send term as default GET variable
});

在服务器端-search-customers.php

$q=$_GET['term'];
$result = // do query;
$json = new Array();
while($row = mysqli_fetch_assoc($result)){
    $json[] = $row['customer_id'];
}
header('Content-type:application/json');
echo json_encode($json);