使用servlet的jQuery自动完成UI没有返回任何数据

3

我已经花费了几个小时来研究这段代码片段,但是我无法理解jQuery的自动完成UI是如何工作的。我按照这个教程 http://viralpatel.net/blogs/tutorial-create-autocomplete-feature-with-java-jsp-jquery/ 的步骤操作。 我使用了相同的示例,但是我使用了一个servlet代替JSP发送请求。请求到达了名为“Fetcher”的servlet,它也被执行了,但是页面上没有返回任何内容。以下是代码。

public class Fetcher extends HttpServlet {
    [...]

    List<String> countryList = new ArrayList<String>();
    String param = request.getParameter("term");

    countryList.add("USA");
    countryList.add("Pakistan");
    countryList.add("Britain");
    countryList.add("India");
    countryList.add("Italy");
    countryList.add("Ireland");
    countryList.add("Bangladesh");
    countryList.add("Brazil");
    countryList.add("United Arab Emirates");
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    response.setHeader("Cache-Control", "no-cache");
     for(String country : countryList){
        out.println(country);
    }

    [...]
}

HTML中的Javascript片段:
 <script>
       $(function() {

         $( "#tags" ).autocomplete({
          source: "Fetcher"

      });
 });
 </script>

HTML表单:

 <label for="tags">Tags: </label>
 <input id="tags" />

这个页面的示例似乎是为熟练掌握jquery的人编写的,http://jqueryui.com/autocomplete/#default。请问有人能详细解释一下它是如何工作的,这样我就可以在其他地方使用它了。


你找到的教程展示了使用 $("#tags").autocomplete("url"),但你正在使用 $("#tags").autocomplete({source:"url"})。如果你有特别原因需要不同于教程的方式进行,请问为什么现在抱怨它不能正常工作呢?你应该使用 $("#tags").autocomplete("Fetcher") - BalusC
1个回答

12
servlet 应该以 JSON 格式返回自动完成数据。有几个选项可供选择,我选择了一个包含标签/值属性对象的数组:
@WebServlet("/autocomplete/*")
public class AutoCompleteServlet extends HttpServlet {
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response) throws ServletException,
            IOException {

        final List<String> countryList = new ArrayList<String>();
        countryList.add("USA");
        countryList.add("Pakistan");
        countryList.add("Britain");
        countryList.add("India");
        countryList.add("Italy");
        countryList.add("Ireland");
        countryList.add("Bangladesh");
        countryList.add("Brazil");
        countryList.add("United Arab Emirates");
        Collections.sort(countryList);

        // Map real data into JSON

        response.setContentType("application/json");

        final String param = request.getParameter("term");
        final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>();
        for (final String country : countryList) {
            if (country.toLowerCase().startsWith(param.toLowerCase())) {
                result.add(new AutoCompleteData(country, country));
            }
        }
        response.getWriter().write(new Gson().toJson(result));
    }
}

要返回自动补全数据,您可以使用此帮助程序类:

class AutoCompleteData {
    private final String label;
    private final String value;

    public AutoCompleteData(String _label, String _value) {
        super();
        this.label = _label;
        this.value = _value;
    }

    public final String getLabel() {
        return this.label;
    }

    public final String getValue() {
        return this.value;
    }
}
在servlet中,真实的数据被映射为适用于jQuery自动完成的表单。我选择了Google GSON将结果序列化为JSON。
相关:
对于在.jsp中实现的HTML文档,请选择正确的库、样式表和样式:
<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"> </script>
        <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

        <script type="text/javascript" src="autoComplete.js"> </script>
    </head>

    <body>
        <form>
            <div class="ui-widget">
                <label for="country">Country: </label>
                <input id="country" />
            </div>
        </form>
    </body>
</html>

相关链接:jQuery自动完成演示


我已经将Javascript函数放在一个单独的文件autoComplete.js中:

$(document).ready(function() {
    $(function() {
        $("#country").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "/your_webapp_context_here/autocomplete/",
                    type: "POST",
                    data: { term: request.term },

                    dataType: "json",

                    success: function(data) {
                        response(data);
                    }
               });              
            }   
        });
    });
});
自动完成功能使用 AJAX 请求调用 Servlet。由于 Servlet 的结果是适当的,因此可以直接用于响应。
相关链接:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接