我搜索了论坛,但没有找到任何答案这个问题。Jquery自动完成 - 结合数据源 - 主要和后备
我正在使用jquery自动填充来填充表单域。
我目前正在使用来自XML文件的本地数据(代码第一部分下面)。 这适用于本地查询所需的答案,但如果本地XML不包含正确的查询结果,我希望有一个后备数据源(JSON geoname - 请参阅下面的代码第二部分)。
我试过并且未能合并这两个数据源,所以为了简单起见,我将它们单独发布在此处。
他们都独立工作 - 但如何将它们合并成一个结果字段? 另外,XML数据应该是主要选择。
代码的一部分ONE
代码为XML本地源
$(document).ready(function() {
var myArr = [];
$.ajax({
type: "GET",
url: "airports.xml",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
function parseXml(xml)
{
//find every query value
$(xml).find("state").each(function()
{
//you are going to create an array of objects
var thisItem = {};
thisItem['label'] = $(this).attr("label") + ', ' + $(this).attr("country");
thisItem['value'] = $(this).attr("iata");
myArr.push(thisItem);
});
}
function setupAC() {
$("#city").autocomplete({
source: myArr,
minLength: 3,
select: function(event, ui) {
$("#city").val(ui.item.iata);
$("#qf").submit();
}
});
}
});
部分代码一个airports.xml文件片段
<states>
<state label="London Heathrow" iata="LHR" country="UK" />
<state label="Syndey" iata="SYD" country="Australia" />
....
代码部分一个搜索表单代码
<label for="city">From</label></td>
CODE第二部分 下面是使用JSON从GEONAMES
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 20,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.geonames, function(item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
再次感谢您的帮助 - 非常感谢。 – SolMan