在springmvc中实现jquery自动完成

时间:2013-05-31 07:06:47

标签: jquery spring spring-mvc jquery-autocomplete

我正在尝试为搜索用户实施自动填充功能

<%@ 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上的示例

1 个答案:

答案 0 :(得分:2)

而不是上面的代码,只需使用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