What does autocomplete request/server response loo

2020-01-27 02:00发布

This seems to be a black hole: After an hour of searching the jQuery UI website, Stack Overflow, and googling, I've yet to find the most basic information of how to write the server side of the AutoComplete.

What parameter is passed to the server and what should the JSON response look like?

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.

I need enough to get the simplest remote example working.

7条回答
等我变得足够好
2楼-- · 2020-01-27 02:52

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.

I have used this functionality using a JSON call like so:

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

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.

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)

查看更多
登录 后发表回答