如何从servlet获取ajax调用的响应

时间:2014-06-30 09:41:34

标签: java jquery ajax servlets

我使用ajax调用了一个servlet。

        $.ajax({
        type: "post",
        url: "FileUploadServlet", //this is my servlet
        dataType: 'json',
        data:{"myJsonString":"myJsonString","aadhar":"aadhar"},
        //data: "myJsonString" ,
        beforeSend: function (request)
        {
            request.setRequestHeader("myJsonString", myJsonString);
            request.setRequestHeader("aadhar", aadhar);

        },
        success: function(response){
            // $('#uidrespon').html(response); 
            //alert(uidrespon);
        } 
        });

从我的servlet我想把响应传递给ajax。为了从servlet发送响应,我使用代码但是我没有通过ajax

获得响应
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json;charset=utf-8");
    PrintWriter out = response.getWriter();
    System.out.println("In doPost");

    String stat="";
    String member_Id="111111111";
    String session_id="121233";



    try{
        System.out.println("In try--------");
        String strrs = request.getHeader("myJsonString");
        String uid_val = request.getHeader("aadhar");
        System.out.println("Uid value..."+uid_val);
        if(strrs!= null){
             stat = "Uploaded Successfully";
             System.out.println("upload status"+stat);
        }else if(strrs == null){
            stat = "Uploaded Failed";
             System.out.println("upload status"+stat);
            request.setAttribute("status", stat);
        }   

        byte[] b = strrs.getBytes();
        System.out.println("In bytes---"+b);
        String encodedString = Base64.encodeBase64(b).toString();
        System.out.println("In image---\n"+encodedString);

         uid_webservice tes = new uid_webservice();

         String src= tes.authenticate(member_Id,uid_val,encodedString,session_id);

         System.out.println("Source------"+src); // Getting return value value from uid_webservice 

         request.setAttribute("uidrespon", src);

         response.setContentType("text/plain");  
         response.setCharacterEncoding("UTF-8"); 
         response.getWriter().write(src);

任何人都可以帮助我...... Thanx提前

1 个答案:

答案 0 :(得分:1)

$.ajax({
    type: "post",
    url: "FileUploadServlet", //this is your servlet
    dataType: 'html',
    data:{
        myJsonString:"myJsonString",
        aadhar:"aadhar"
    },
    success: function(response){
         $('#uidrespon').html(response); 
        //alert(uidrespon);
    } 
    });

Servlet方:

request.setAttribute("src", src); 
response.setCharacterEncoding("UTF-8"); 
response.getWriter().print(src);

我认为它必须有效。