带有 servlet 的 jQuery autocomplete UI 不返回任何数据

jQuery autocomplete UI with servlet is not returning any data

本文关键字:返回 任何 数据 UI autocomplete servlet jQuery 带有      更新时间:2023-09-26

在过去的几个小时里,我一直在摆弄这个代码片段,但我无法理解jQuery的自动完成UI是如何工作的。我遵循了本教程 http://viralpatel.net/blogs/tutorial-create-autocomplete-feature-with-java-jsp-jquery/我使用了相同的示例,但我没有向JSP发送请求,而是使用了servlet。请求到达servlet "Fetcher",它也执行,但没有任何东西返回给页面。这是代码。

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>

网页表单:

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

页面上的示例似乎是为jquery中的专业人士编写的,http://jqueryui.com/autocomplete/#default。拜托,有人能告诉它到底是如何工作的,以便我可以在其他地方使用它。

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 自动完成的形式。我选择了谷歌GSON将结果序列化为JSON。

相关:

  • 了解和实现使用 AJAX 源代码和 appendTo 的 Jquery 自动完成
  • 如何从 Java Servlet 返回 JSON 对象

至于HTML文档(在.jsp中实现),请选择正确的库,样式表和样式:

<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 的结果是合适的,因此可以按原样用于响应。

相关:

  • jQuery UI Autocomplete的"source"回调中的"响应"和"请求"参数是什么?
  • jQuery 自动完成小部件
  • jQuery ajax 函数