简体   繁体   中英

Using jQuery autocomplete with non-standard options?

I'd like to use jQuery's auto complete in a Drupal project to automatically find nodes (pieces of content) with a given title. I can't quite find any examples of option usage that match what I am trying to do, which is the following:

  1. URL needs to conform to the pattern: /api/node/title/{whatever the user typed}
  2. When results are returned as JSON, the title needs to be used in the auto complete list
  3. When a result is clicked, a styled paragraph containing the title will appear over the text box, but it will actually contain the node id (nid) of the node selected.

Here is what I have so far:

jQuery(this).autocomplete({
    source: '/api/node/title/'+jQuery(this).val(),
    minLength: 2
}).data( "autocomplete")._renderItem = function(ul, item) {
    return jQuery('<li />')
        .data("item.autocomplete", item)
        .appendTo(ul);
};

I haven't even gotten to worrying about what to do once an element is selected - the URL is going out as /api/node/title?term={blank}, and even though I am getting JSON results back, nothing is appearing. Any suggestions, or examples of similar usage? The examples on the jQuery UI website for autocomplete weren't especially helpful.

EDIT: Here is an example of the expected response.

{
    "nid":"2",
    "vid":"2",
    "type":"lorem",
    "language":"und",
    "title":"Grid Computing",
    "uid":"0",
    "status":"1",
    "created":"1320092886",
    "changed":"1320273538",
    "comment":"1",
    "promote":"1",
    "sticky":"0",
    "tnid":"0",
    "translate":"0"
}

for 1), you can use a callback for the source

$('input').autocomplete({
    source: autoDrupal,
    minLength: 2});

function autoDrupal(requestObject, responseCallback) {
   var url = '/api/node/title/' + requestObject.term;
   $.get(url, function(data) {
       // check my fiddle to transform drupal response in autocomplete result ;)
       responseCallback(data);
   });
};

for 2) I don't get what you mean by "title" but it can surely be handled in the response of $.get for 3) a event handler can do the trick (once I understand your dreaded "title"). something like that:

$('ul.ui-autocomplete').delegate('li', 'click', function () {
    $('#stuff').css('color', 'red');
})

check and play with this fiddle ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM