将变量从servlet传递给ajax

时间:2014-04-17 18:58:14

标签: javascript jquery ajax servlets

我开发了一个投票明星基础系统,当用户投票时,我发送一个ajax请求给我的servlet放置数据库更新

这是我的ajax代码:

 $.ajax({
            type:'GET',
            contentType: "charset=utf-8",
            url:''+encodeURI('/RecommandationDefault/rating?track='+surat+'&recitateur='+recitateur+'&vote='+voteVal),
            success:function(resp){
                alert(response);
            }


        });

这是我的servlet的代码

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String n1=new String(request.getParameter("track").getBytes("ISO-8859-1"),"UTF-8");
        System.out.println("track"+n1);
                String n2=request.getParameter("recitateur");
        String n3=request.getParameter("vote");
        try {
            DaoLastfm D = new DaoLastfm();
            D.insert_vote(n2, n1, n3);
            // processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(rating.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

插入工作完美无缺,

我担心的是,在插入数据库后,servlet如何转发到变量中的javascript内容?

1 个答案:

答案 0 :(得分:0)

只需将变量打印到servlet中的响应:

PrintWriter out = response.getWriter();
out.write(variable);

通过决定是否要将变量称为resp或response来修复Ajax成功方法中的拼写错误:

        success:function(response){
            alert(response);
        }