2012-10-21 32 views
1

我是AJAX的新手,正在尋找更好的方法來完成此操作。我有一個搜索框,搜索大約10,000個字符串的數組中的字符串。代碼如下,但速度太慢。當然有更好的方法。它是什麼 ??下面是HTML和javascript在大型數據上執行AJAX搜索的更好方法

<script> 
    function showHint(str) 
    { 
    var xmlhttp; 
    if (str.length==0) 
     { 
     document.getElementById("txtHint").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) 
     { 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
     } 
     } 
    xmlhttp.open("GET","gethint.php?q="+str,true); 
    xmlhttp.send(); 
    } 
    </script> 


    <body> 
    <h3>Start typing a name in the input field </h3> 
    <form action=""> 
    First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> 
    </form> 
    <p>Suggestions: <span id="txtHint"></span></p> 
    </body> 

這裏是PHP代碼:

include_once("array.php"); //array.php contains array of 10,000 strings 

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

//lookup all hints from array if length of q>0 
if (strlen($q) > 0) 
    { 
    $hint=""; 
    for($i=0; $i<count($a); $i++) 
    { 
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) 
     { 
     if ($hint=="") 
     { 
     $hint=$a[$i]; 
     } 
     else 
     { 
     $hint=$hint." , ".$a[$i]; 
     } 
     } 
    } 
    } 

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

//output the response 
echo $response; 
+6

使用數據庫和LIMIT子句。 –

+0

你有沒有想過使用像MySQL這樣的數據庫? –

+0

查詢了大約26個不同的MySQL數據庫後,創建了字符串數組。 – silverflash

回答