我有一个适用于城市搜索字段的jquery脚本 脚本
<script type="text/javascript">
$(document).ready(function()
{
var ac_config =
{
source: "demo_cities.php",
select: function(event, ui)
{
$("#City").val(ui.item.City);
$("#Country").val(ui.item.Country);
$("#DestinationId").val(ui.item.DestinationId);
},
minLength:3
};
$("#City" ).autocomplete(ac_config);
});
</script>
和php代码是
<?php
$cities= array(
array('City'=>'Barcelona',
Country=>'SP',
DestinationId=>'10001'),
....... );
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $City)
{
if(stripos($City['City'], $term) !== false)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
如何让脚本仅按城市名称中的前3个字符进行搜索
答案 0 :(得分:1)
在您的PHP代码中,您正在寻找一个包含城市名称中的字符串的城市。如果您想要显示以特定字符开头的城市,您可以使用substr
<?php
$cities= array(
array('City'=>'Barcelona',
'Country'=>'SP',
'DestinationId'=>'10001'
),
//more cities ...
);
$term = strtolower(trim(strip_tags($_GET['term'])));
$matches = array();
foreach($cities as $City)
{
if(strtolower(substr($city['city'], 0, strlen($term))) == $term)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
答案 1 :(得分:0)
通常城市不会更改其名称,所以我将城市名称放在js文件中,然后让FE进行搜索, 和自动完成部分似乎毫无疑问。