开发者

How to handle servlet response in JSP through AJAX call?

开发者 https://www.devze.com 2023-03-11 16:53 出处:网络
I want to display servlet response in my JSP page (as a hyperlink) through an ajax call. Can anyone please tell me how I could display the content in my jsp page? I am also not too sure if I am doing

I want to display servlet response in my JSP page (as a hyperlink) through an ajax call. Can anyone please tell me how I could display the content in my jsp page? I am also not too sure if I am doing it the right way. There could be some errors in either my servlet class or Ajax.js. I'm still in learning phase. Here is my code snippet:

JSP page

<script type="text/javascript"> var AJAX_SERVLET="<%=renderResponse.encodeURL(renderRequest.getContextPath())%>/ajaxServlet"; </script> <label for="push">Push to start</label> <button dojoType="dijit.form.Button" style="width: 4em" type="button" name="submitButton" value="Submit" onclick="ajaxFunction()"></button>

Ajax.js

function ajaxFunction() {
    if (xmlhttp) {
    xmlhttp.open("GET", AJAX_SERVLET, true); //AJAX_SERVLET has the servlet path
    xmlhttp.onreadystatechange = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type',
            'application/x-www-form-urlencoded');
    xmlhttp.send(null);
}

}

function handleServerResponse() { if (xmlhttp.readyState == 4) { //alert(xmlhttp.status); if (xmlhttp.status == 200) { var resultContent =httpRequest.getResp开发者_开发问答onseHeader("Content-Type");

} else { alert("Error during AJAX call. Please try again"); } }

Getters/Setters

public class SearchResponse {

private String productNumber;
private String productType;
private String funcDesignation;}

Servlet Class

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    List result = new ArrayList();
    result.add(new SearchResponse("001", "User Manual", "Operator"));
    response.setContentType("application/json");         
    response.setCharacterEncoding("UTF-8");        
    response.getWriter().write(new Gson().toJson(result));
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    doPost(request, response);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消