我正在尝试根据用户从jQuery自动填充字段中选择的Suburbs选项,使用来自mySQL数据库的数据填充邮政编码(即邮政编码)输入字段。
自动完成工作正常 - 根据用户的输入术语检索过滤的Suburbs列表。源引用是一个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/(这是我最接近我的问题,虽然它根据状态选择填充了一系列zipcodes的邮政编码或邮政编码字段,而不是基于一个郊区/城市的单个邮政编码。) / p>
任何帮助表示赞赏。 非常感谢你, 安德鲁
答案 0 :(得分:1)
我已将完全这个功能构建到我的应用程序中。这里还有一层额外的复杂性,因为有两个郊区查找(家庭和工作地址),每个都填充匹配的状态和邮政编码字段。后端是perl而不是PHP,但这与客户端处理无关。最终后端返回一个JSON结构,其中包含一系列哈希:
[ { "id":"...", "value":"...", "state":"...", "pcode":"..." }, ... ]
id键包含郊区名称,值键包含“JOLIET IL 60403”等字符串,因此选择正确的设置数据一次,解决了多个城镇/郊区的问题在不同的地方使用相同的名称,并进行回拨以解决此问题。
选择后,郊区(id),州和pcode值将被注入匹配参数。
以下代码还会缓存以前的结果(并在主页和工作查找之间共享缓存)。
$('#hm_suburb').addClass('suburb_search').attr(
{suburb: '#hm_suburb', pcode: '#hm_pcode', state: '#hm_state'});
$('#wk_suburb').addClass('suburb_search').attr(
{suburb: '#wk_suburb', pcode: '#wk_pcode', state: '#wk_state'});
var sub_cache = {};
$(".suburb_search").autocomplete({
source: function(request, response) {
if (request.term in sub_cache) {
response($.map(sub_cache[request.term], function(item) {
return { value: item.value, id: item.id,
state: item.state, pcode: item.pcode }
}))
return;
}
$.ajax({
url: suburb_url,
data: "term=" + request.term,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
sub_cache[request.term] = data;
response($.map(data, function(item) {
return {
value: item.value,
id: item.id,
state: item.state,
pcode: item.pcode
}
}))
} //,
//error: HandleAjaxError // custom method
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
$this = $(this);
//alert("this suburb field = " + $this.attr('suburb'));
$($this.attr('suburb')).val(ui.item.id);
$($this.attr('pcode')).val(ui.item.pcode);
$($this.attr('state')).val(ui.item.state);
event.preventDefault();
}
}
});
答案 1 :(得分:0)
在select
函数中,您将要启动另一个ajax请求。这个新的ajax请求会将当前选定的郊区发送到另一个php脚本,该脚本将返回该郊区的邮政编码。在与此ajax请求关联的回调中,将返回的邮政编码填入表单。
您需要使用jQuery.get来触发新的ajax请求: http://api.jquery.com/jQuery.get/
select: function(event, ui) {
$.get("postcodes.php", { suburb: $("#suburbs").val },
function(postCodes) {
// use data in postCodes to fill in your form.
}, "json");
}
postcodes.php将获取$ _GET ['suburb']并返回一些包含该郊区邮政编码的json结构。
答案 2 :(得分:0)
我明白了。谢谢大家。
此外,我发现以下内容非常接近我的目标:
http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/
相关的jQuery:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source: "SuburbStatePostcodeRetriever.php",
select: function(event, ui){
$("#suburb").val(ui.item.locality);
$("#state").val(ui.item.state);
$("#postcode").val(ui.item.postcode);
},
minLength:3
};
$("#suburb").autocomplete(ac_config);
});
</script>
HTML:
<form action="#" method="post">
<p><label for="city">Suburb</label><br />
<input type="text" name="city" id="suburb" value="" /></p>
<p><label for="state">State</label><br />
<input type="text" name="state" id="state" value="" /></p>
<p><label for="zip">Postcode</label><br />
<input type="text" name="zip" id="postcode" value="" /></p>
</form>
PHP:
<?php
// connect to database
$con = mysql_connect("********","********","********");
if (!$con) { die('Could not connect: ' . mysql_error()); }
$dbname = '********';
mysql_select_db($dbname);
$initialSuburbsArray = array( );
$result = mysql_query("SELECT locality, postcode, state FROM ********",$con) or die (mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$initialSuburbsArray[] = $row;
}
$suburbs = $initialSuburbsArray;
// Cleaning up the term
$term = trim(strip_tags($_GET['term']));
// get match
$matches = array();
foreach($suburbs as $suburb){
if(stripos($suburb['locality'], $term) !== false){
// Adding the necessary "value" and "label" fields and appending to result set
$suburb['value'] = $suburb['locality'];
$suburb['label'] = "{$suburb['locality']}, {$suburb['postcode']} {$suburb['state']}";
$matches[] = $suburb;
}
}
// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);
mysql_close($con);
?>
可能需要更多改进,但主要是它。感谢。