24H免费课程咨询  TEL:13401595960   QQ:1870218756  微信:13401595960(李老师)

东方博宜

网站首页 > 软件开发资讯 > Java开发

[常州Java培训]jsp+servlet+json+ajax传递数据

2017-12-03 16:43:42 东方博宜 阅读

json的使用

http://www.w3school.com.cn/json/

作用,如果要返回多个数据,使用json格式的字符串返回,前端jquery ajax可以直接解析为对象!

 

JSON的格式:

单个对象:{ "firstName":"Bill" , "lastName":"Gates" }

多个对象:

{

"employees": [

{ "firstName":"Bill" , "lastName":"Gates" },

{ "firstName":"George" , "lastName":"Bush" },

{ "firstName":"Thomas" , "lastName":"Carter" }

]

}

 

A、返回单个的json对象

index.jsp

                   <input type="button" value="获取信息"/>

                  

                  

                   <script src="js/jquery-1.11.3.js"></script>

                   <script>

                       $(document).ready(function(){

                                     $("[value='获取信息']").click(function(){

                                                                      //检验逻辑

                                    $.ajax({

                                        //后台地址

                                        url:"GetMessageServlet"

                                        ,

                                        //提交方式:getpost

                                        type:"post"

                                        ,

                                        dataType:"json",    //数据类型为json格式

                                        //data表示我们需要向后台传递的参数

                                        data:{

                                           r:Math.random()

                                        }

                                        ,

                                        //ajax处理结束(data表示后台的返回值)

                                        success:function(data,status){

                                            alert(data.realname + " " + data.username + " " + data.gender);

                                        }

                                    });

 

                                     });       

                       });

                   </script>

 

GetMessageServlet

         public void doPost(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

 

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

                   request.setCharacterEncoding("utf-8");

                   PrintWriter out = response.getWriter();

                   JSONObject resultJSON = new JSONObject();// 构建一个JSONObject

                   resultJSON.accumulate("username", "admin");

                   resultJSON.accumulate("realname", "管理员");

                   resultJSON.accumulate("gender", "");

 

                   response.setContentType("application/x-json");// 需要设置ContentType

                                                                                                                                  // "application/x-json"

                   out.println(resultJSON.toString());// 向客户端输出JSONObject字符串

 

                   out.flush();

                   out.close();

         }

 

B、返回JSON数组

index.jsp

                   <input type="button" value="获取信息"/>

                  

                  

                   <script src="js/jquery-1.11.3.js"></script>

                   <script>

                       $(document).ready(function(){

                                     $("[value='获取信息']").click(function(){

                                                                      //检验逻辑

                                    $.ajax({

                                        //后台地址

                                        url:"GetMessageServlet"

                                        ,

                                        //提交方式:getpost

                                        type:"post"

                                        ,

                                        dataType:"json",    //数据类型为json格式

                                        //data表示我们需要向后台传递的参数

                                        data:{

                                           r:Math.random()

                                       }

                                        ,

                                        //ajax处理结束(data表示后台的返回值)

                                        success:function(data,status){

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

                                               alert(data.users[i].userno + " " + data.users[i].username + " " + data.users[i].realname);

                                            }

                                        }

                                    });

 

                                     });       

                       });

                   </script>

 

GetMessageServlet

         public void doPost(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

 

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

                   request.setCharacterEncoding("utf-8");

                   PrintWriter out = response.getWriter();

                  

                   Map m1 = new HashMap();

                   m1.put("userno", 1);

                   m1.put("username", "admin");

                   m1.put("realname", "管理员");

                  

                   Map m2 = new HashMap();

                   m2.put("userno", 2);

                   m2.put("username", "lisi");

                   m2.put("realname", "李四");

                  

                   List list = new ArrayList();

                   list.add(m1);

                   list.add(m2);

                  

                   //JSON数组

                   JSONArray arr = JSONArray.fromObject(list);

                  

JSONObject json = new JSONObject();

                   json.accumulate("users", arr);

                   response.setContentType("application/x-json");// 需要设置ContentType

                                                                                                                                   // "application/x-json"

                   out.println(json.toString());// 向客户端输出JSONObject字符串

 

                   out.flush();

                   out.close();

         }

 

注意:

JSON相关的包的下载:链接: https://pan.baidu.com/s/1nvmTl7F 密码: 9yws

图片.png

Powered by 东方博宜教育咨询江苏有限公司  ©2008-2017 www.czos.cn