我尝试了很多东西,但我不明白这太令人困惑。
我有这个
<input id="wba" type="search" name="q" value="" class="search box" />
<input type="submit" value="Go" class="search button" />
也 一个php文件
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$arr = array('test'=>'hello world');
echo json_encode($arr);
至于javascript我已经尝试了一切,包括来自jquery网站的演示,但没有运气......那里有人帮我设置自动完成功能来显示数据?
修改
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
$("#wba").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.sites, function(item) {
alert(item);
window.console.debug(item);
return {
label: item.name ,
value: item.url
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? ("Selected: " + ui.item.name) : "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");
}
});
});
此代码来自jqueryui网站(演示)......
答案 0 :(得分:1)
它应该是这样的
// JS
$(function() {
$("#wba").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: { q: request.term },
success: function(data) {
response($.map(data, function(value,key) {
return { label:value.label , value: value.val }
}));
}
});
},
minLength: 2
});
});
// PHP
$results = array(
array('label' =>'label1', 'val' => 'value1'),
array('label' =>'label2', 'val' => 'value2'),
array('label' =>'label3', 'val' => 'value3')
);
// Optionally do something with the user input ($_GET["input_value"])
echo $_GET['callback'].'('.json_encode($result).');'
我不知道为什么但这确实有用......
答案 1 :(得分:0)
没有任何代码的基本前提是:
有很多不同的方法可以实现这一点,这就是为什么我没有用实际功能回答的原因。这取决于你的目标。
答案 2 :(得分:0)
以下是我在服务器上使用C#实现它的方法。
<强>的JavaScript 强>
function InitializeElement (element) {
element.autocomplete("ServerPage.ashx", {
formatItem: function(data) {
return "<span style=\"font-size:9pt;word-break:break-all;\">" + data[0] + "<br />" + data[1] + "</span>";
}
});
element.result(function(event, data, formatted) {
jq(event.currentTarget).siblings('input[type=hidden]').val(data[2]);
event.currentTarget.value = data[0];
event.currentTarget.title = data[1];
});
}
<强> C#强>
public class ServerPage : ApplicationHandler
{
protected override void Process()
{
String text = (this.Request.Params["q"] ?? String.Empty);
if (text.Length > 0)
{
using (DatabaseRecords records = this.Core.Database.ExecuteRecords("StoredProcedure", new KeyValue("Text", text)))
{
while (records.Read())
{
Response.Write(records.GetString("Code") + "|" + records.GetString("Description") + "|" + records.GetInt32("Id") + "\n");
}
}
}
}
}