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

时间:2013-06-07 09:10:49

标签: javascript ajax google-maps servlets

我正在尝试处理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+"}");
}

很抱歉,如果这一切都不那么清楚!

1 个答案:

答案 0 :(得分:1)

(在问题编辑中由OP回答。转换为社区维基答案。请参阅Question with no answers, but issue solved in the comments (or extended in chat)

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);
            }
        });
    };
}