简体   繁体   English

使用json ajax javascript jquery和java(没有PHP)的自动完成搜索栏

[英]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). 我正在尝试实现类似于facebook的自动完成搜索栏(例如单击特定结果时的下拉结果,它应直接指向相应的链接)。

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. 我已经可以执行自动完成功能(搜索结果仅显示文本),但是我不确定如何将各个链接/ URL链接到结果。

Any help is much appreciated. 任何帮助深表感谢。 Thank you. 谢谢。

Below is my searchjson method for java which I have linked to routes as 'GET' method. 以下是我的java的searchjson方法,我已将其链接为“ GET”方法。

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 下面是我的自动完成JavaScript

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 ) {} 选择: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 因此,您谈论重定向,在这种情况下,您可以使用window.location重定向到该页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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