Java 从servlet获取数据到ajax?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20549292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:42:45  来源:igfitidea点击:

Getting data from servlet to ajax?

javajqueryajaxjspservlets

提问by Cata Visan

Jsp / servlets seems to be much more tedious than I'd have expected it. I'm trying to call a servlet function through ajax and actually have it feed some data back to my front end , which is a jsp file.

Jsp/servlets 似乎比我预期的要乏味得多。我正在尝试通过 ajax 调用一个 servlet 函数,实际上让它将一些数据反馈给我的前端,这是一个 jsp 文件。

This code returns my response as null.

此代码将我的响应返回为空。

This is part of my servlet. I'm trying(desperately as is fairly obvious from the code) to have it send something - anything back to ajax.

这是我的 servlet 的一部分。我正在尝试(绝望地从代码中很明显)让它发送一些东西 - 任何东西回 ajax。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = (String) request.getParameter("action");
if (action.equalsIgnoreCase("selectedhotel"))
    {

        response.setContentType("text/plain");  
        response.setCharacterEncoding("UTF-8"); 
        System.out.println("test");
        String attribute = (String) request.getParameter("hotel_id");
        System.out.println(attribute);
        List<Room> aRooms;
        aRooms = model.getRoomByHotel(Integer.valueOf(attribute));
        request.setAttribute("aRooms", aRooms);
        request.setAttribute("list", list);
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write("ASDSADA");
            outPrintWriter.println("test");
    }   

And the ajax from my JSP:

还有来自我的 JSP 的 ajax:

$(function(){
$("#hotelSelector li").click(function(){        
    var hid = $(this).attr('id');

    $.ajax({ type: "GET",   
         url: "AppController?action=selectedhotel&hotel_id=1",   
         success : function(text)
         {
            alert(text);
             // This will show the values. Change "alert" for $('div#mydiv').html(value) or so
         }
    });
});
});</script>

Riiight...so , please fix ?

Riiight...所以,请修复?

采纳答案by Russell Shingleton

As mentioned, you really need to start small and work your way up. Get a simple "hello world" ajax response working and then tackle the more complex responses. For the more complex data response, I would recommend looking into json (see gson) to serialize the java objects in order to send back in the response writer.

如前所述,您确实需要从小处着手,然后逐步提高。获得一个简单的“hello world”ajax 响应,然后处理更复杂的响应。对于更复杂的数据响应,我建议查看 json (请参阅gson)以序列化 java 对象,以便在响应编写器中发回。

First thing you should consider is using the jQuery post and get wrappers to make your life easier.

您应该考虑的第一件事是使用 jQuery 帖子并获取包装器以使您的生活更轻松。

For example, your html would be like the following:

例如,您的 html 将如下所示:

<h1>Hello: <span style="color:red" id="showMyName"></span></h1>
<form method="post" action="AjaxServlet" id="myForm">
    <input type="text" name="myName" />            
</form>
<button id="ajaxSubmit" type="submit">SEND</button>
<script type="text/javascript">
     $(document).ready(function() {
        $('#ajaxSubmit').on('click', function() {
        // To simplify things, wrap what you can in a form and serialize                      
        // it to send to the server.
            var myForm = $('#myForm');
            $.get(myForm.attr('action'), myForm.serialize(), function(data) {
                $('#showMyName').text(data);
            });
        });
    });
</script>

On the servlet side, you should start with a plain-jane servlet and once you are sure it is working, begin adding additional scope. The base servlet should be somthing like this:

在 servlet 方面,您应该从一个普通的 jane servlet 开始,一旦您确定它可以工作,就开始添加额外的作用域。基本 servlet 应该是这样的:

// For this example, get and post will use the same base procedures.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
}

protected void processRequest(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your response here.*/
        out.println(request.getParameter("myName"));
    } finally {
        out.close();
    }
}

One way to send a complex response is to shove all your data in a collection of some sort and use gson or some other JsonObjectMapper to convert it to a string. You can then put this String in the response writer and send it back to be parsed out by jQuery.

发送复杂响应的一种方法是将所有数据放入某种集合中,并使用 gson 或其他一些 JsonObjectMapper 将其转换为字符串。然后,您可以将此字符串放入响应编写器并将其发送回以供 jQuery 解析。

EDIT:

编辑:

I forgot to mention that you need to make sure your servlet is being recognized by the your servlet container as well. If you haven't added the descriptor to the web.xml, it should have an entry like the following:

我忘了提到你需要确保你的 servlet 也被你的 servlet 容器识别。如果您还没有将描述符添加到 web.xml,它应该有如下条目:

<servlet>
    <servlet-name>AjaxServlet</servlet-name>
    <servlet-class>org.test.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AjaxServlet</servlet-name>
    <url-pattern>/AjaxServlet</url-pattern>
</servlet-mapping>

回答by vikasramireddy

xmlhttp.responseText is used in javascript to get the response from a servlet. how you are getting response in jquery. i think problem is in retrieving the response

xmlhttp.responseText 在javascript 中用于从servlet 获取响应。您如何在 jquery 中获得响应。我认为问题在于检索响应