这是我的Jquery自动完成代码,它不适用于动态数据。我有json数据作为标签:联系人姓名和值:联系人ID但这个自动完成功能不适用于AJAX调用。
$("#autocomplete2").autocomplete({
//source: data,
source: function (request, response) {
$.ajax({
type: "POST",
url: "http://localhost/leadata.php",
dataType: "json",
data: { q: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.label,
value: el.value
};
});
alert(transformed);
response(transformed);
},
error: function () {
response([]);
}
});
},
response: function (event, ui) {
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
},
focus: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
},
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
$("#autocomplete2-value").val(ui.item.value);
alert(ui.item.value);
//$('.college').trigger('click');
}
});
答案 0 :(得分:0)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
</style>
<script>
$(function() {
$( "#birds" ).autocomplete({
source: "http://localhost/autocomplete/test.php",
minLength: 2,
response: function(event, ui) {
if (ui.content.length === 0) {
$("#empty-message").text("+ Add Contact");
} else {
$("#empty-message").empty();
}
},
focus: function(event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
},
select: function( event, ui ) {
/*
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
*/
event.preventDefault();
//$(this).val(ui.item.label);
$("#birdsval").val(ui.item.label);
$("#birdsid").val(ui.item.value);
//$('.college').trigger('click');
$(this).val('');
},
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds"><br />
<input id="birdsid">
<input id="birdsval">
</div>
<div id="empty-message"></div>
</body>
</html>
答案 1 :(得分:0)
以下是test.php的PHP代码
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("databasename", $conn);
$q = strtolower($_GET["term"]);
$return = array();
$query = mysql_query("select id,firstname from tablename where firstname like '%$q%'");
while ($row = mysql_fetch_array($query)) {
array_push($return,array('label'=>$row['firstname'],'value'=>$row['id']));
}
echo(json_encode($return));
?>