我试图填充邮政编码(即邮政编码)输入字段从MySQL数据库中的数据,根据用户选择的选项来自jQuery自动填充字段的郊区。jQuery的自动完成和PHP:填充输入字段基于在自动填充字段中选择选项从MySQL数据库中的数据
自动完成工作正常 - 过滤的郊区列表是基于从用户输入词检索。源参考是一个PHP文件。但我无法弄清楚如何使用用户选择的选项回调数据库来检索邮编。可能邮政编码可以在第一次调用来检索,同时为郊区:除了我不希望所有的邮政编码,只需用户最终选择的一个。
我jQuery是如下:(该 “$( '#邮政编码')” 行不工作尚未...)
<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);
?>
我发现thse链接可能是最有帮助的:
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/(这是最接近我的问题,虽然它填充的邮政编码或邮政编码场与基于状态的选择范围邮编,而不是基于单个邮政编码一个郊区/城市)。
任何帮助表示赞赏。 谢谢你, 安德鲁
谢谢..仍然让我的脑海里的东西.. –
嗯,重要的是,虽然你的AJAX调用自动完成*必须*返回'ID'和'值',你不仅限于这些属性。我还返回'state'和'postcode',以更改其他表单元素。 – RET