我试图实现输入字段,该输入字段在键入时显示建议。我已经找到了jquery自动完成功能,但是我正在努力将XML作为来自php的数据源。我的PHP文件创建一个这样的输出。使用php输出xml作为数据源的自动完成
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<locations>
<location>
<number>600</number>
<name>Location Name 600</name>
</location>
<location>
<number>698</number>
<name>Location Name 698</name>
</location>
<location>
<number>1110</number>
<name>Location Name 1110</name>
</location>
</locations>
我已经张贴罗里McCrossan链接尝试过。
我的HTML现在看起来是这样的:
<!DOCTYPE HTML>
<head>
<title>Autocomplete</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#output");
$("#output").scrollTop(0);
}
$.ajax({
url: "api.php",
dataType: "xml",
success: function(xmlResponse) {
var data = $("location", xmlResponse).map(function() {
return {
name: $("name", this).text(),
number: $("number", this).text()
};
}).get();
$("#locations").autocomplete({
source: data,
minLength: 0,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.name + ", number: " + ui.item.number :
"Nothing selected, input was " + this.value);
}
});
}
});
});
</script>
</head>
<body style="background-color: black; color: white;">
<input id="locations" />
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="output" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
当我写的东西到输入字段,然后清除它,它让我看到3华里的下方的输入字段(这是我的位置量,根据XML),但没有文字显示在他们旁边。出了什么问题?
这也适用于url:“api.php”而不是xml文件吗? – Ahatius
是的,只要您包含'dataType:“xml”'设置来将预期格式显式设置为XML。 –
自动填充方法存在一些问题,请参阅打开文章。 – Ahatius