我创建了一个自动填充搜索框,并且只显示名称列表,我想使用xml文件显示所有数据。例如 - 姓名,城市,国家等 怎么解决这个......?请帮帮我。
我的代码是...... 在HTML中
<form name="search_form" id="searchForm" method="GET" action="search_results.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />
<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>
和jquery
$(document).ready(function() {
var myArr = [];
$.ajax({
type: "GET",
url: "data.xml", // change to full path of file on server
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("info").each(function()
{
myArr.push($(this).attr("name"));
});
}
function setupAC() {
$("input#searchBox").autocomplete({
source: myArr,
minLength: 1,
select: function(event, ui) {
$("input#searchBox").val(ui.item.value);
$("#searchForm").submit();
}
});
}
});
和xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<info name="jatin" value="IP" city="Pune" country="india" />
<info name="kishor" value="WY" city="Mumbai" country="india" />
<info name="rahul" value="AL" city="Latur" country="india" />
<info name="dnyanesh" value="WY" city="punjab" country="india" />
</data>
答案 0 :(得分:0)
试试这个,
$.ajax({
type: "GET",
url: "data.xml", // change to full path of file on server
dataType: "xml",
success: function(xml) {
parseXml(xml); // calling parseXml and pass xml into it.
setupAC();
},
failure: function(data) {
alert("XML File could not be found");
}
});
使用代码段
更新了城市/国家/地区名称搜索
$(function() {
var myArr = [],
xml = '<?xml version="1.0" encoding="UTF-8"?><data><info name="jatin" value="IP" city="Pune" country="india" /><info name="kishor" value="WY" city="Mumbai" country="india" /><info name="rahul" value="AL" city="Latur" country="india" /><info name="dnyanesh" value="WY" city="punjab" country="india" /></data>';
function parseXml(xml) {
//find every query value
$(xml).find("info").each(function() {
myArr.push({
name: $(this).attr('name'),
city: $(this).attr('city'),
country: $(this).attr('country'),
value: $(this).attr('value')
});
});
}
function setupAC() {
$("input#searchBox").autocomplete({
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(myArr, function(v) {
return matcher.test(v.name) || matcher.test(v.city) || matcher.test(v.country);
}));
},
minLength: 1,
select: function(event, ui) {
$("input#searchBox").val(ui.item.value);
}
});
}
parseXml(xml);
setupAC();
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input id="searchBox" type="text">