在servlet中返回json数据

在servlet:

String name = new tring(request.getParameter("name").getBytes("iso8859-1"),"utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
 //拼接json数据
String jsonStr = "{\"name\":\""+name+"\",\"age\":\"20\"}";
 //将数据写入流中
response.getWriter().write(jsonStr);

js:

<script>
    $(function(){
        $.post("${ pageContext.request.contextPath }/servlet/jsonServlet",{"name":"赵子龙"},function(result){
                        //遍历
            $.each(result, function(i, field){
              $("#divbox").append(i+":"+field + ";");
            });
        });
        
//         $.getJSON("${ pageContext.request.contextPath }/servlet/jsonServlet",function(result){
//             $.each(result, function(i, field){
//               $("#divbox").append(i+":"+field + ";");
//             });
        
//         }); 
        
    })
    </script>            

 

posted @ 2017-06-19 17:05  大大大圣  阅读(9174)  评论(0编辑  收藏  举报