【发布时间】:2011-11-16 15:04:32
【问题描述】:
我正在尝试根据用户从 jQuery 自动完成字段中选择的 Suburbs 选项,使用来自 mySQL 数据库的数据填充 Postcode(即邮政编码)输入字段。
自动完成功能正常 - 根据用户输入的术语检索过滤后的郊区列表。源参考是一个 PHP 文件。但是我不知道如何使用用户选择的选项来回调数据库以检索邮政编码。可能可以在第一次调用中检索到邮政编码,同时检索郊区:除了我不想要所有的邮政编码,只想要用户最终选择的那个。
我的 jQuery 如下:("$('#postcodes')" 行还不能工作......)
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.15.custom.min.js"></script>
<script>
// autocomplete
$(function() {
$( "#suburbs" ).autocomplete({
source: "allSuburbs.php",
minLength: 3,
select: function( event, ui ) {
$('#postcodes').val(ui.item.postcode);
},
});
});
</script>
相关html:
<p>Suburb</p><input class="inputText" type="text"
size="50" name="term" id="suburbs" maxlength="60" /></td>
<td><p>State</p><input class="inputText" type="text"
size="5" name="" id="states" maxlength="4" /></td>
<td><p>Postcode</p><input class="inputText" type="text"
size="5" name="" id="postcodes" maxlength="4" /></td>
PHP (allSuburbs.php):
<?php
$con = mysql_connect("***","***","***");
if (!$con) { die('Could not connect: ' . mysql_error()); }
$dbname = 'suburb_state';
mysql_select_db($dbname);
$query = "SELECT name FROM suburbs";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" . mysql_error());
//retrieving the search term that autocomplete sends
$qstring = "SELECT name FROM suburbs WHERE name LIKE '%".$term."%'";
//query the database for entries containing the term
$result = mysql_query($qstring);
//loop through the retrieved values
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{ $row['name']=htmlentities(stripslashes($row['name']));
$row['postcode']=htmlentities(stripslashes($row['postcode']));
$row_set[] = $row['name'];//build an array
}
echo json_encode($row_set);//format the array into json data
mysql_close($con);
?>
我发现这些链接可能最有帮助:
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/ (这最初对我有帮助)
http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/(这是最接近我的问题,尽管它根据州选择使用一系列邮政编码填充邮政编码或邮政编码字段,而不是基于一个郊区/城市的单个邮政编码)。
任何帮助表示赞赏。 非常感谢你, 安德鲁
【问题讨论】: