简体   繁体   中英

Getting data from servlet to ajax?

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.

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.

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:

$(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 ?

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.

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

For example, your html would be like the following:

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

// 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM