简体   繁体   中英

Autocomplete search bar using json ajax javascript jquery and java (no PHP)

I am trying to implement the autocomplete search bar similar to facebook (like the drop down results when clicked on a particular result, it should direct to the respective link).

I have got the autocomplete thing working (search results displaying only text) but I am not sure how to link the respective links/urls to the results.

Any help is much appreciated. Thank you.

Below is my searchjson method for java which I have linked to routes as 'GET' method.

public static Result searchJSON(String query) {
    List<Account> userAccs = searchAccounts(query);
    ObjectNode json = Json.newObject();
    ArrayNode jsonArray = json.putArray("");
    ObjectNode node = null;
    for(Account acc : userAccs) {
        node = jsonArray.addObject();
        node.put("label", acc.getDisplayName());
        node.put("id", acc.getId());
    }
    return ok(jsonArray);

Below is my javascript for autocomplete

var SearchBar = (function($) {
var search_data = function( request, response ) {
    $.ajax({
        url: "/search.json",
        dataType: "json",
        type: "GET",            
        data: {q: request.term },
        success: function( data ) {
            response( $.map( data, function( item ) {
                return {
                    label: item.label,
                    id: item.id
                  };
               }));
           }
       });
    };

    $("#searchfield").autocomplete({
        source: search_data,
        minLength: 1
     }); 

  return {
      attach: attach_to_bar
  };

}) (jQuery);

On your autocomplete constructor you can use the option

select: function( event, ui ) {}

that gets fired when you select an item. So you can then do whatever you like.

So you talk about redirecting, in that case you can redirect to that page with window.location

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