处理ajax和java servlet之间的请求和响应

Handle request and response between ajax and java servlet

本文关键字:请求 求和 响应 之间 servlet ajax java 处理      更新时间:2023-09-26

我试图处理ajax和servlet之间的请求/响应:用户单击一个Google地图标记,并通过ajax调用使用他的id的相对于标记的评论。

这应该是Ajax代码

 function infoCallback(infowindow, marker) {
    return function() {
        $.ajax({
            type: 'POST',
            url: 'commentListener',
            data: {
                id: marker.id,
                comment:$('#comment').val()
            },
            success:function(data){
                var comment = $('#output').html(data);
                infowindow.setContent(comment);
                infowindow.open(map, marker);
            }
        });
    };
}

这应该是Servlet代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long id = Long.parseLong(request.getParameter("id"));
    String comment = //comment relative to the id
    /*Way to send the comment to the infowindow*/
    response.getWriter().write("{comment:"+comment+"}");
}

对不起,如果这一切都不是很清楚!

(OP在问题编辑中回答)转换成社区维基的答案。参见没有答案的问题,但问题已在评论中解决(或在聊天中扩展))

OP写:

使用PrintWriter

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long id = Long.parseLong(request.getParameter("id"));
    String comment = //get comment by id
    try {  
        PrintWriter out;
        out = response.getWriter();  
        out.print(comment);
    } catch (IOException e) {  
        e.printStackTrace();  
    }
}

这是ajax

function infoCallback(infowindow, marker) {
    return function() {
        $.ajax({
            type: 'POST',
            url: 'commentListener',
            data: {
                id: marker.id,
            },
            success:function(result){
                infowindow.setContent(result);
                infowindow.open(map, marker);
            }
        });
    };
}