Java WEB

12.5 JQuery 异步请求返回JSON数据

  • Servlet 返回json数据

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

                   List<Employee> emps = new EmployeeDaoJdbcImpl().getAllEmps();

                   Gson gson = new Gson();

                   String jsonStr = gson.toJson(emps);

                   response.setContentType("text/html;charset=utf-8");

                   PrintWriter out = response.getWriter();

                   out.println(jsonStr);

                   out.close();

}

  • 页面中处理 json数据

function getJsonStr(){

                   //通过JQuery发送异步请求, 将所有的员工信息通过json的格式返回

 $.ajax({

         url:"getEmpsJsonStr",

         type:"post",

         dataType:"json",

         success:function(data){  // 会直接将后台返回的json字符串转换成js对象

                   var str = "<tr><th>Id</th><th>LastName</th><th>Email</th><th>Gender</th></tr>";

                   for(var i= 0 ;i <data.length;i++){

                            var emp = data[i];

                            str+="<tr align='center'><td>"

                 +emp.id+

                 "</td><td>"

                 +emp.lastName+

                 "</td><td>"

                 +emp.email+

                 "</td><td>"

                 +emp.gender+

                 "</td></tr>"       

                   }       

                                     $("#tb").html(str);

                            }

                   });

         }

 

<body>

         <input type="button" value="getJsonStr" onclick="getJsonStr();"/>

         <table id="tb" border="1px"  align="center" width="60%" cellspacing="0px"

         </table>

</body>