简体   繁体   English

处理Ajax和Java Servlet之间的请求和响应

[英]Handle request and response between ajax and java servlet

I'm trying to handle the request/responde between ajax and a servlet: The user click on a Google map marker, and through ajax he call the comment relative to the marker using his id. 我正在尝试处理ajax和servlet之间的请求/响应:用户单击Google地图标记,然后通过ajax使用其ID调用相对于标记的注释。

this should be the Ajax code 这应该是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);
            }
        });
    };
}

and this should be the Servlet code 这应该是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+"}");
}

Sorry if all this is not so clear! 对不起,如果还不清楚的话!

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) ) (由OP在问题编辑中回答。转换为社区Wiki答案。请参阅无答案的问题,但问题已在评论中解决(或扩展为聊天)

The OP wrote: OP写道:

SOLVED 解决了

Using PrintWriter 使用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();  
    }
}

and this is the 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);
            }
        });
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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