Skip to content

Instantly share code, notes, and snippets.

@abriening
Created September 13, 2010 13:32
Show Gist options
  • Save abriening/577278 to your computer and use it in GitHub Desktop.
Save abriening/577278 to your computer and use it in GitHub Desktop.
/*
* Extend the Ajax.Autocompleter
*
* Defaults to using a json response.
*
* If the response looks like html, send it to the updateChoices() function.
* Otherwise assume it is json and build the unordered list from the json array.
* If you set the header to 404 when there are no results, the onComplete() function is not called.
*/
Object.extend(Ajax.Autocompleter.prototype, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
// Only accept json or html
this.options.requestHeaders = {'Accept': 'application/json, application/xhtml+xml, text/html'};
},
// Added to allow json response rather than html
parseResponse: function(responseText){
if (responseText.include('<ul>')){
// html response just return the text
return responseText;
} else {
// assume it is json and parse/build
var collection = eval(responseText.strip());
var ul = document.createElement('ul');
collection.each(function(entry, index) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(entry));
ul.appendChild(li);
});
return "<ul>" + ul.innerHTML + "</ul>";
}
},
onComplete: function(request) {
this.updateChoices(this.parseResponse(request.responseText));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment