Reputation: 3396
Currently trying to implement an autocomplete on a clients website which searches through products and textpages. For this, I've made a generic handler that returns anonymous objects as JSON. My anonymous object looks like this:
new
{
Name = product.Name,
Url = product.Url,
ImageUrl = imageUrl
});
The list of objects gets serialized with a standard .NET JavascriptSerializer.
And my javascript looks like this:
searchField.autocomplete({
source: "/handlers/SearchHandler.ashx",
response: function (event, ui) {
...
}
});
I'm a bit stuck when it comes to getting the values from JSON into the autocomplete dropdownbox though. Also, I want to use the results as links, so when the user clicks on a result in the dropdown, he/she gets redirected to the page/product.
Does anyone know how to achieve this?
Solution:
searchField.autocomplete({
source: "/handlers/SearchHandler.ashx?nodeId=" + currentNodeId,
search: function (event, ui) {
searchField.css("background-image", "url('../img/ajax-loader-small.gif')");
},
response: function (event, ui) {
searchField.css("background-image", "");
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a href='" + item.Url + "'>" + item.Name + "</a>")
.appendTo(ul);
};
Upvotes: 1
Views: 3594
Reputation: 3271
You are trying to use the sample for a static source for a dynamic purpose.
Your source-property should not be a url
, but a function
:
.autocomplete({
source: function( request, response ) {
$.getJSON( "/handlers/SearchHandler.ashx", {
term: extractLast( request.term )
}, response );
}, ...
})
.data( "autocomplete" )._renderItem = function( ul, product ) {
return $( "<li>" )
.append( "<a href=" + product.Url + ">" + product.Name + "</a>" )
.appendTo( ul );
};
The correct samples are found here (source) and here (custom display).
Based on the comments, only alter your rendering to handle your products-response (see the second link).
Upvotes: 2