簡體   English   中英

在springmvc中實現jquery自動完成

[英]Implementing jquery autocomplete in springmvc

我正在嘗試為搜索用戶實現自動完成功能

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript"        src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Insert title here</title>
<script type='text/javascript' src="js/jquery.autocomplete.js"></script
<link rel="stylesheet" type="text/css" href="js/jquery.autocomplete.css" />
<script type="text/javascript">
$(document).ready(function(){
        $('#search').keyup(function() { 
        var search  = $('#search').val();
         if(search.length>2){   
            $.ajax({
                 type:"POST",
                 url: "searchuser",
                 cache:false,
                 data: 'search=' + $("#search").val() ,
                 success: function(response){               
                    $.each(response, function (index, value) {
                            alert(value);
                     }
                    );
                 },
                error: function(e){
                 alert('Error: ' + e);
                 }
                });
         }
     });
 });
 </script>   
</head>
 <body>
 <form>
   <input id="search" type="text"  name="search" />
  </form>
  </body>
 </html>

我從數據庫獲取值並能夠使用alert彈出值但我想使用該值實現自動完成任何人都可以建議我如何使用spring MVC上的示例

而不是上面的代碼,只需使用jqueryUI autocompete功能。 它將為您提供所需的所有句柄。

$( "#search" ).autocomplete({
  source: "searchuser",
  minLength: 3,
  select: function( event, ui ) {

    console.log( ui.item ?
      "Selected: " + ui.item.value + " aka " + ui.item.id :
      "Nothing selected, input was " + this.value );
  }
});

在服務器端,

@RequestMapping(value = "/searchuser", method = RequestMethod.GET)
public void searchUser(HttpServletResponse response,@RequestParam Map<String, String> params) {
    String jsonResponse = null;
    //Get params.get("term") --> It will be search criteria
    String jsonResponse= "[{\"fname\":\"atul\",\"userId\":1,\"name\":\"atul  kumar\",\"value\":\"atul  kumar\",\"label\":\"atul  kumar\"}]";                    
    response.setContentType("application/json");
    try {
        response.getOutputStream().print(jsonResponse);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

PS:在返回的JSON中,標簽和值很重要,因為標簽顯示在下拉列表中,值是默認設置為輸入文本。 您也可以使用其他值(如示例中所示)。 可以在select:functions(event,ui){}中進行進一步處理

希望它能夠消除疑慮。 您還應該檢查jqueryUI的API和demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM