带有servlet的jQuery自动完成UI没有返回任何数据 [英] jQuery autocomplete UI with servlet is not returning any data

查看:90
本文介绍了带有servlet的jQuery自动完成UI没有返回任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been fiddling with this code fragment from past few hours but I am unable to understand how jQuery's autocomplete UI works. I followed this tutorial http://viralpatel.net/blogs/tutorial-create-autocomplete-feature-with-java-jsp-jquery/ I used same example but instead of sending request to a JSP, I used a servlet. The request reaches the servlet "Fetcher", it executes as well but nothing is returned to the page. Here's the code.

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片段:

Javascript fragment in HTML:

 <script>
       $(function() {

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

      });
 });
 </script>

HTML表格:

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

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

The examples on the page seems written for a pro in jquery, http://jqueryui.com/autocomplete/#default . Please, could someone tell how exactly it works, so that I can use it in other places.

推荐答案

servlet 应该将自动填充数据作为JSON返回。有几个选项,我选择了一个包含带标签/值属性的对象的数组:

The servlet should return the autocomplete data as JSON. There a several options, I have opted for an array which contains an object with label/value properties:

@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:

to return the autocomplete data, you could use this helper class:

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。

so in the servlet, the real data is mapped into a form suitable for jQuery's autocomplete. I have selected Google GSON to serialize the result as JSON.

相关:

  • Understanding and Implementing Jquery autocomplete with AJAX source and appendTo
  • How do you return a JSON object from a Java Servlet

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

As for the HTML document (implemented in a .jsp), pick the correct libraries, stylesheets and styles:

<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

I have put the Javascript functions in a separate file 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的结果是合适的,它可以按原样用于响应。

The autocomplete function uses an AJAX request to call the servlet. As the result of the servlet is suitable, it can be used as-is for the response.

相关:

  • What are the "response" and "request" arguments in jQuery UI Autocomplete's "source" callback?
  • jQuery autocomplete widget
  • jQuery ajax function

这篇关于带有servlet的jQuery自动完成UI没有返回任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆