jQuery 自动完成请求/服务器响应是什么样的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5077409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does autocomplete request/server response look like?
提问by Pete Alvin
This seems to be a black hole: After an hour of searching the jQuery UIwebsite, Stack Overflow, and googling, I've yet to find the most basic information of how to write the server sideof the AutoComplete.
这似乎是一个黑洞:在jQuery UI网站、Stack Overflow 和谷歌搜索了一个小时后,我还没有找到如何编写AutoComplete服务器端的最基本信息。
What parameter is passed to the server and what should the JSON response look like?
传递给服务器的参数是什么,JSON 响应应该是什么样的?
I must be missing something, because how did everyone else learn how to do this? Sites only seem to discuss the client-side JavaScript code and never the protocol or server-side examples.
我一定遗漏了一些东西,因为其他人是如何学会如何做到这一点的?站点似乎只讨论客户端 JavaScript 代码,从不讨论协议或服务器端示例。
I need enough to get the simplest remote example working.
我需要足够的东西来让最简单的远程示例工作。
回答by Andrew Whitaker
What parameter is passed to the server
传递给服务器的参数是什么
You need to pass request.term
to your server-side code (from the documentation):
您需要传递request.term
给您的服务器端代码(来自文档):
A request object, with a single property called "term", which refers to the value currently in the text input.
一个请求对象,有一个名为“term”的属性,它指的是当前文本输入中的值。
Basically, in your autocomplete
code, you'll have something like this:
基本上,在您的autocomplete
代码中,您将拥有如下内容:
$("#autocomplete").autocomplete({
// request.term needs to be passed up to the server.
source: function(request, response) { ... }
});
and what should the JSON response look like?
JSON 响应应该是什么样的?
The autocomplete
widget expects an array of JSON objects with label
and value
properties (although if you just specify value
, it will be used as the label). So in the simplest case, you can just return data that looks like this:
该autocomplete
小部件需要一个带有label
和value
属性的 JSON 对象数组(尽管如果您只指定value
,它将用作标签)。因此,在最简单的情况下,您可以只返回如下所示的数据:
[
{ label: 'C++', value: 'C++' },
{ label: 'Java', value: 'Java' }
{ label: 'COBOL', value: 'COBOL' }
]
If you need something more complicated, you can use the success
argument of the $.ajax
function to normalize the data you get back before the autocomplete gets it:
如果你需要更复杂的东西,你可以使用函数的success
参数$.ajax
来规范化你在自动完成之前得到的数据:
source: function( request, response ) {
$.ajax({
/* Snip */
success: function(data) {
response($.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
This code is taken from the example here(This is a good example overall of ajax + autocomplete works in a more complex scenario).
此代码取自此处的示例(这是 ajax + 自动完成在更复杂场景中工作的一个很好的示例)。
Basically, what's going is that upon a successful ajax request, the data received is being normalized (using $.map
) to what the autocomplete widget expects.
基本上,发生的事情是在成功的 ajax 请求后,接收到的数据被标准化(使用$.map
)到自动完成小部件所期望的。
Hope that helps.
希望有帮助。
回答by James Boyden
In addition to Andrew Whitaker's perfect answer, an alternative method to $.map is to override the renderer, an example of which is shown on the jQuery UI Demo page.
除了 Andrew Whitaker 的完美答案之外,$.map 的另一种方法是覆盖渲染器,jQuery UI 演示页面上显示了一个示例。
I have used this functionality using a JSON call like so:
我已经通过 JSON 调用使用了此功能,如下所示:
JSON Response
{ "Records": [ { "WI_ID": "1", "Project": "ExampleProject", "Work_Item": "ExampleWorkItem", "Purchase_Order": "", "Price": "", "Comments": "", "Quoted_Hours": "", "Estimated_Hours": "", "Achieved": "False", "Used_Hours": "0" } ] }
jQuery
$("#WorkItem").autocomplete({ source: function(request, response){ $.ajax({ type: "POST", url: "ASPWebServiceURL.asmx/WorkItems", data: "{'Project_ID':'1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { response($.parseJSON(msg.d).Records); }, error: function (msg) { alert(msg.status + ' ' + msg.statusText); } }) }, select: function (event, ui) { $("#WorkItem").val(ui.item.Work_Item); return false; } }) .data("autocomplete")._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.Work_Item + "</a>") .appendTo(ul); };
JSON 响应
{ "Records": [ { "WI_ID": "1", "Project": "ExampleProject", "Work_Item": "ExampleWorkItem", "Purchase_Order": "", "Price": "", "Comments": "", "Quoted_Hours": "", "Estimated_Hours": "", "Achieved": "False", "Used_Hours": "0" } ] }
jQuery
$("#WorkItem").autocomplete({ source: function(request, response){ $.ajax({ type: "POST", url: "ASPWebServiceURL.asmx/WorkItems", data: "{'Project_ID':'1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { response($.parseJSON(msg.d).Records); }, error: function (msg) { alert(msg.status + ' ' + msg.statusText); } }) }, select: function (event, ui) { $("#WorkItem").val(ui.item.Work_Item); return false; } }) .data("autocomplete")._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.Work_Item + "</a>") .appendTo(ul); };
In this example, the _renderItem function is overridden so that the search result list (i.e, the list that appears under the textbox) is filled using attributes of the records that I retrieved from the JSON response.
在此示例中,_renderItem 函数被覆盖,以便使用我从 JSON 响应中检索到的记录的属性填充搜索结果列表(即,出现在文本框下方的列表)。
Whilst not as simple, it allows you to pull off some pretty interesting stuff (using multiple bits of data from a JSON response, for example)
虽然不是那么简单,但它允许您完成一些非常有趣的事情(例如,使用来自 JSON 响应的多位数据)
回答by Brian Ogden
Both answers so far are complex and misleading, a key understanding to jQuery UI Auto Complete is the success anonymous function, you have leverage/control of the format of your server side JSON response because of the success callback of AutoComplete. The label,value format is a good one to follow but you can define any JSON format you desire, the key is how you define your success function:
到目前为止,这两个答案都很复杂且具有误导性,对 jQuery UI Auto Complete 的一个关键理解是成功匿名函数,由于 AutoComplete 的成功回调,您可以利用/控制服务器端 JSON 响应的格式。label,value 格式是一个很好的遵循,但你可以定义任何你想要的 JSON 格式,关键是你如何定义你的成功函数:
<input id="refPaymentTerms" class="form-control">
$("#refPaymentTerms").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "/admin/JobPaymentRefs",
dataType: "json",
data: {
term: request.termCode
},
error: function (xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.responseText);
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}));
}
});
}
});
MVC Controller:
MVC控制器:
public JsonResult JobPaymentRefs()
{
var query = from REFTerm in _db.REFTerms
select new
{
label = REFTerm.TermCode,
value = REFTerm.TermCode
};
//var refTerms = _db.REFTerms.Select(x => x.TermCode);
return Json(query.ToArray());
}
Here we see a very standard auto complete bind with an ASP.NET backend.
在这里,我们看到了一个非常标准的自动完成与 ASP.NET 后端的绑定。
You can return whatever format of JSON you desire server side as long as you map it correctly in the AutoComplete anonymous callback. The label,value name value pair is good enough for most requirements but do as you will server side with your JSON just map it correctly in the AutoComplete success callback.
只要您在自动完成匿名回调中正确映射它,您就可以返回您希望服务器端使用的任何格式的 JSON。标签,值名称值对足以满足大多数要求,但您将在服务器端使用 JSON 进行操作,只需在 AutoComplete 成功回调中正确映射它即可。
回答by Salman A
You are notrequired to tweak the server side script in order to use jQuery UI autocomplete. You can specify a JavaScript function as the source
to create custom requests (e.g. use POST or GET, use query string parameters that the serever side script expects) and handle arbitrary responses (e.g. handle XML responses).
你是不是需要调整服务器端脚本,以使用jQuery UI自动完成。您可以指定一个 JavaScript 函数source
来创建自定义请求(例如使用 POST 或 GET,使用服务器端脚本期望的查询字符串参数)并处理任意响应(例如处理 XML 响应)。
Having said that, when you use a string as the source
parameter, then:
话虽如此,当您使用字符串作为source
参数时,则:
[...] the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a termfield, which the server-side script should use for filtering the results. For example, if the source option is set to
http://example.com
and the user types foo, a GET request would be made tohttp://example.com?term=foo
. The data itself can be in the same format as the local data described above.
[...] Autocomplete 插件期望该字符串指向将返回 JSON 数据的 URL 资源。它可以在同一台主机上,也可以在不同的主机上(必须提供 JSONP)。Autocomplete 插件不会过滤结果,而是添加了一个带有term字段的查询字符串,服务器端脚本应该使用它来过滤结果。例如,如果 source 选项设置为
http://example.com
并且用户键入 foo,则会向 发出 GET 请求http://example.com?term=foo
。数据本身可以采用与上述本地数据相同的格式。
Regarding "The data itself can be in the same format as the local data described above", the following JSON (or JSONP) formats will work:
关于“数据本身可以采用与上述本地数据相同的格式”,以下 JSON(或 JSONP)格式将起作用:
// no matching entries
[]
// array of strings
[
"Option 1",
"Option 2"
]
// array of objects with label property
[{
"label": "Option 1"
}, {
"label": "Option 2"
}]
// array of objects with value property
[{
"value": "Option 1"
}, {
"value": "Option 2"
}]
// array of objects with label and value properties
[{
"label": "Option 1",
"value": 1
}, {
"label": "Option 2",
"value": 2
}]
For the arrays of objects, you are free to specify additional properties besides label and/or value
. All properties will be available inside callbacks.
对于对象数组,您可以自由指定除 label 和/或 之外的其他属性value
。所有属性都将在回调中可用。
回答by Nava Bogatee
The following code is working for me. This needs json encoded data to work. Once we get data, it modifies it according to jQuery autocomplete format and also enables selection
以下代码对我有用。这需要 json 编码的数据才能工作。获取数据后,它会根据 jQuery 自动完成格式对其进行修改并启用选择
var $url = "http://some-url/get-json";
//name is the id of the textbox where autocomplete needs to be shown
$('#name').autocomplete(
{
source: function(request,response)
{
//gets data from the url in JSON format
$.get($url, function(data)
{
obj = JSON.parse(data); //parse the data in JSON (if not already)
response($.map(obj, function(item)
{
return {
label: item.full_name,
value: item.full_name,
id:item.id,
email:item.email,
phone:item.phone,
}
}
)); //end response
}); //end get
},
select:function(event, ui)
{
console.log(ui.item.full_name);
console.log(ui.item.email);
}
}); //end of autocomplete
回答by caot
The following Autocomplete is from https://jqueryui.com/autocomplete/#remote-jsonp
以下自动完成来自https://jqueryui.com/autocomplete/#remote-jsonp
A demo link: https://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html
演示链接:https: //jqueryui.com/resources/demos/autocomplete/remote-jsonp.html
Here is source code:
这是源代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote JSONP datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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 src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
} );
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
回答by Hari Agarwal
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Categories</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
body {
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
font-size: 62.5%;
}
</style>
<script>
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu : function(ul, items) {
var that = this, currentCategory = "";
$.each(items, function(index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
</script>
<script>
$(function() {
$("#search").catcomplete({
delay : 0,
source : function(request, response) {
$.ajax({
url : "search",
dataType : "json",
data :"searchText=hk",
success : function(data) {
response(data);
} //success
});
}
});
});
</script>
</head>
<body>enter code here
<label for="search">Search: </label>
<input id="search" />
</body>
</html>