自动填充请求/服务器响应是什么样的?

这似乎是一个黑洞:在searchjQuery UI网站,堆栈溢出和谷歌search一个小时后,我还没有find如何编写AutoComplete的服务器端的最基本的信息。

什么parameter passing给服务器,JSON响应应该是什么样的?

我一定会错过一些东西,因为其他人怎么学到这个呢? 网站似乎只讨论客户端的JavaScript代码,而不讨论协议或服务器端的例子。

我需要足够的最简单的远程示例工作。

什么parameter passing给服务器

您需要将request.term传递给您的服务器端代码(从文档中):

一个请求对象,带有一个名为“term”的属性,它引用了当前在文本input中的值。

基本上,在你的autocomplete代码中,你会有这样的东西:

 $("#autocomplete").autocomplete({ // request.term needs to be passed up to the server. source: function(request, response) { ... } }); 

那么JSON响应应该是什么样子呢?

autocomplete小部件需要具有labelvalue属性的JSON对象数组(尽pipe如果您只指定了value ,它将用作标签)。 所以在最简单的情况下,你可以返回如下所示的数据:

 [ { label: 'C++', value: 'C++' }, { label: 'Java', value: 'Java' } { label: 'COBOL', value: 'COBOL' } ] 

如果您需要更复杂的东西,可以使用$.ajax函数的success参数来标准化您在自动完成获取之前获得的数据:

 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 } })); } }); 

这段代码取自这里的例子(这是在更复杂的场景中ajax +自动完成工作的一个很好的例子)。

基本上,一个成功的ajax请求发生了什么,接收到的数据正在被标准化(使用$.map )自动完成小部件的期望。

希望有所帮助。

除了Andrew Whitaker的完美答案之外,$ .map的一个替代方法是重写渲染器, 在jQuery UI Demo页面上显示了一个例子。

我已经使用这样的function使用JSON调用:

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); }; 

在这个例子中,_renderItem函数被覆盖,这样search结果列表(即出现在文本框下面的列表)将使用从JSON响应中检索到的logging的属性来填充。

虽然不是那么简单,它可以让你得到一些非常有趣的东西(例如使用来自JSON响应的多位数据)

这两个答案到目前为止是复杂和误导,对jQuery UI自动完成的关键理解是成功的匿名函数,您有杠杆/控制您的服务器端JSON响应的格式,因为成功的callbackAutoComplete。 标签,值的格式是一个很好的遵循,但你可以定义任何你想要的JSON格式,关键是你如何定义你的成功function:

  <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控制器:

 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()); } 

在这里,我们看到一个非常标准的自动完成绑定与ASP.NET后端。

只要您在AutoComplete匿名callback中正确映射,就可以返回任何您希望服务器端的JSON格式。 对于大多数需求来说,标签,值名称值对就足够了,但是您可以像使用JSON一样在服务器端进行映射,只需在AutoComplete成功callback中正确映射即可。

你不需要调整服务器端脚本,以使用jQuery UI自动完成。 您可以指定一个JavaScript函数作为创build自定义请求的source (例如,使用POST或GET,使用serever侧脚本期望的查询string参数)并处理任意响应(例如处理XML响应)。

话虽如此,当你使用一个string作为source参数,那么:

[…]自动完成插件希望该string指向将返回JSON数据的URL资源。 它可以在同一个主机上或不同的主机上(必须提供JSONP)。 自动填充插件不会过滤search结果,而是在查询string中添加一个术语字段,服务器端脚本应该使用该术语字段来过滤结果。 例如,如果source选项设置为http://example.com ,并且用户键入foo,则会向http://example.com?term=foo发出GET请求。 数据本身可以采用与上述本地数据相同的格式。

关于“数据本身可以采用与上述本地数据相同的格式” ,以下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 }] 

对于对象数组,您可以自由指定除标签和/或value之外的其他属性。 所有的属性都将在callback中提供。

 <!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> 

以下代码正在为我工​​作。 这需要json编码的数据才能工作。 一旦我们获得数据,它会根据jQuery自动完成格式对其进行修改,并启用select

 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