2010-08-12 62 views
0

我有mysql表是這樣的:jQuery的自動完成

country | city_accented | latitude | longitude | 
--------------------------------------------------------- 
australia | sydney  | -33.8833333 | 151.2166667 | 
    USA | dallas  | 35.3163889 | -81.1763889 | 

我使用jQuery自動完成獲得在表單文本字段國名。 如何使用這個jquery函數發佈數據庫中的所有其他數據(經度,緯度,...)到我的表單並像隱藏字段那樣使用它?

jQuery代碼:

function lookup(inputString) { 
if(inputString.length == 0) { 
    // Hide the suggestion box. 
    $('#suggestions').hide(); 
} else { 
    $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ 
     if(data.length >0) { 
      $('#suggestions').show(); 
      $('#autoSuggestionsList').html(data); 
     } 
    }); 
} 
} // lookup 

function fill(thisValue) { 
$('#inputString').val(thisValue); 
$('#suggestions').hide(); 
} 

HTML:

<input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" /> 
<div class="suggestionsBox" id="suggestions" style="display: none;"> 
<div class="suggestionList" id="autoSuggestionsList"></div> 

PHP:

if(isset($_POST['queryString'])) { 
$queryString = $_POST['queryString'];  
if(strlen($queryString) >0) { 
$query = "SELECT * FROM cities WHERE city_accented LIKE '$queryString%' LIMIT 10"; 
$result = mysql_query($query) or die("There is an error in database"); 
while($row = mysql_fetch_array($result)){ 
echo '<li onClick="fill(\''.$row['city_accented'].'\');">'.$row['city_accented'].','.$row['country'].' </li>';           
} 
} 
} 

回答

0

而不是發佈HTML回來,我只想發佈此JSON對象和構建在客戶端需要html。所以,你可以得到你的陣列從mysql回電並提交回:

$return_results = array(); 

while($row = mysql_fetch_array($result)) 
{ 
$return_results[] = $row;      
} 

echo json_encode($return_results); 

然後在JavaScript代碼中你可以用數組做任何你想用的數據。創建li項目。用數據創建隱藏字段。隨你。