Jquery自动完成与JSP json



我试图在我的网站上使用http://jqueryui.com/autocomplete/#multiple-remote,但我不能得到它给出正确的结果。

我的HTML是:

<input id="movies-text" size="50" />
我的Jquery代码是:
$('#movies-text').autocomplete({
    minLength:3,
    source:function(request,response){
        $.getJSON('searchmovies.jsp',{q:request.term},function(result){
            response($.map(result,function(item){
                return item.value;
            }));
        });
    }
});

searchmovies.jsp看起来像这样:

<%@ page contentType="application/json" language="java" import="java.sql.*" errorPage="" %>
<%
   response.setContentType("application/json");
   response.setHeader("Content-Disposition", "inline");
%>
[
    {"value":"Pulp fiction"},
    {"value":"The hobbit"},
    {"value":"Apocalypse Now"},
    {"value":"As good as it gets"},
    {"value":"Annie hall"},
    {"value":"Butch Cassidy and the sundance kid"},
    {"value":"Terminator"}
]

无论i是什么类型,它都会给出下拉列表中的所有值

对于您的情况,您有两个选择,

Option1:基于请求项填充json(最佳方法)

您的jsp响应应该与查询字符串匹配,这里您盲目地将所有值填充为响应,但它应该基于您的请求字符串。

例如,

如果您的输入字符串是"Pulp",那么jsp应该只返回

 [{"value":"Pulp fiction"}}

没有什么可抱怨的jQuery的工作基于它的性质,你需要调整你的服务器端json产生基于输入查询的输出。

Option2:添加一个过滤器到整个填充对象

考虑这个例子test.html,

<html>
<head>
    <title>jQuery UI Autocomplete - Remote Data functionality with Filter</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <script>
function loadData(){
    var movie_elements;
    $('#movies-text').autocomplete({
        minLength:3,
        source:function(request,response){
           $.getJSON('searchmovies.jsp',{q:request.term},function(result){
            movie_elements = $.map(result,function(item){return item.value;});
            response( $.ui.autocomplete.filter(movie_elements, extractLast( request.term ) ) );
           });
        }
    });
}
function split( val ) {
            return val.split( /,s*/ );
        }
function extractLast( term ) {
            return split( term ).pop();
        }
    </script>
</head>
<body onload="loadData();">
<input id="movies-text" size="50" />
</body>
</html>

选一个最适合你的