如何在 JQueryUI 自动完成中使用 source: function() ... 和 AJAX

我在 JQueryUI 自动完成方面需要一点帮助。我希望我的文本字段(.suggest-user)从一个 AJAX 请求显示名称。这就是我所拥有的:

jQuery("input.suggest-user").autocomplete({
source : function(request, response) {
var name = jQuery("input.suggest-user").val();
jQuery.get("usernames.action?query=" + name, function(data) {
console.log(data);  // Ok, I get the data. Data looks like that:
test = data;        // ["one@abc.de", "onf@abc.de","ong@abc.de"]
return test;        // But what now? How do I display my data?
});
},
minLength : 3
});

非常感谢你的帮助。

262574 次浏览

在 AJAX 回调中,需要调用 response函数; 传递包含要显示的项的数组。

jQuery("input.suggest-user").autocomplete({
source: function (request, response) {
jQuery.get("usernames.action", {
query: request.term
}, function (data) {
// assuming data is a JavaScript array such as
// ["one@abc.de", "onf@abc.de","ong@abc.de"]
// and not a string
response(data);
});
},
minLength: 3
});

如果响应 JSON 与 jQuery UI autocomplete 接受的格式不匹配,那么在将结果传递给响应回调之前,必须在 AJAX 回调中转换结果。看看这个问题和公认的答案.

$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});

试试这个代码。你可以用 $.get代替 $.ajax

$( "input.suggest-user" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'Get',
url: 'yourURL',
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
// hide loading image


response( $.map( data, function(item) {
// your operation on data
}));
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function() {},
close: function() {},
focus: function(event,ui) {},
select: function(event, ui) {}
});

.ASPX页面:

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {


response(data.d);
}
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>

.ASPX.CS代码隐藏文件中:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}


[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");


SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
con.Open();
cmd.Parameters.AddWithValue("@Name", username);
SqlDataReader dr = cmd.ExecuteReader();


while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}

这是一个全新的带有 AJAX 调用示例的工作代码。

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>


<div>
<div id="project-label">Select a project (type "j" for a start):</div>
<img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
<input id="project" />
<input type="hidden" id="project-i" />
</div>




@*Auto Complete*@
<script>
$(function () {


$("#project").autocomplete({
minLength: 0,
source : function( request, response ) {
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts/1/comments",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response( data );
}
});
},
focus: function (event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.email);


return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a> " + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
});
</script>

设置自动完成:

$("#searchBox").autocomplete({
source: queryDB
});

获取数据的 source 函数:

function queryDB(request, response) {
var query = request.term;
var data = getDataFromDB(query);
response(data); //puts the results on the UI
}

当你问到:

引用 //但是现在怎么办? 如何显示我的数据? 引用

你需要映射一个对象数组,这样:

response([{label: 'result_name', value: 'result_id'},]);

这样,当你使用自动完成插件的选择事件时,你可以看到下面的结果;

Result of the select event

您可以这样使用 select 事件:

jQuery("#field").autocomplete({
source: function (request, response) {


},
minLength: 3,
select: function(event, ui)
{
console.log(ui);
}
});

我希望它可以帮助和补充的答案。

$("#subject_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "api/listBasicsubject",
dataType: "json",
type: "post",
data: {
search: request.term
},
success: function(data) {


if (!data.length) {
var result = [{
label: 'Subject not found',
value: response.term
}];
response(result);
} else {
//response(data.data);
response($.map(data.data, function(item) {
return {
label: item.subject_name,
value: item.subject_id
}
}));
}
}
});
},
change: function(event, ui) {
if (ui.item == null) {
$("#subject_name").val("");
$("#subject_code").val("");
$("#subject_name").focus();
}
},


minLength: 0,
classes: {
"ui-autocomplete": "auto_compl-cat"
},


focus: function(event, ui) {
event.preventDefault();
// $("#subject_name").val(ui.item.label);


$("#subject_name").val(ui.item.label);


},


select: function(event, ui) {
if (ui.item.label == "Subject not found") {


$("#subject_name").val('');
$("#subject_code").val('');
event.preventDefault();
return false;
}
//console.log( "Selected: " + ui.item.label + " aka " + ui.item.value);
$("#subject_name").val(ui.item.label);
$("#subject_code").val(ui.item.value);
return false;
}
});