Java Web ajax与json

霸气de小男生 提交于 2020-03-08 22:24:59

 

ajax的概念:

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

ajax运行原理:

页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到      服务器端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回      给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面功能。

 

主要分为js原生的ajax 技术:

js原生的Ajax其实就是围绕浏览器内内置的Ajax引擎对象进行学习的,要使用js原生的Ajax完成异步操作,有如下几个步骤:

1)创建Ajax引擎对象

2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)

3)绑定提交地址

4)发送请求

5)接受响应数据

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 
 7 <script type="text/javascript">
 8 
 9     function fn1(){
10         //get方法
11         //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
12         var xmlHttp = new XMLHttpRequest();
13         //2、绑定监听 ---- 监听服务器是否已经返回相应数据
14         xmlHttp.onreadystatechange = function(){
15             if(xmlHttp.readyState==4&&xmlHttp.status==200){
16                 //5、接受相应数据
17                 var res = xmlHttp.responseText;
18                 document.getElementById("span1").innerHTML = res;
19             }
20         }
21         //3、绑定地址
22         xmlHttp.open("GET","ajaxServlet?name=lisi",true);
23         //4、发送请求
24         xmlHttp.send();
25         
26     }
27     function fn2(){
28         //post 方法
29         //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
30         var xmlHttp = new XMLHttpRequest();
31         //2、绑定监听 ---- 监听服务器是否已经返回相应数据
32         xmlHttp.onreadystatechange = function(){
33             if(xmlHttp.readyState==4&&xmlHttp.status==200){
34                 //5、接受相应数据
35                 var res = xmlHttp.responseText;
36                 document.getElementById("span2").innerHTML = res;
37             }
38         }
39         //3、绑定地址
40         xmlHttp.open("POST","ajaxServlet",false);
41         //4、发送请求  post方法传递参数 必须调用下面的代码才能传递成功
42         xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
43         xmlHttp.send("name=wangwu");
44         
45     }
46 
47     
48 </script>
49 
50 </head>
51 <body>
52     <input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1"></span>
53     <br>
54     <input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2"></span>
55     <br>
56     <input type="button" value="测试按钮" onclick="alert()">
57 </body>
58 </html>
post 和 get 方法测试

 

 1 package com;
 2 
 3 import java.io.IOException;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 /**
11  * Servlet implementation class AjaxServlet
12  */
13 @WebServlet("/ajaxServlet")
14 public class AjaxServlet extends HttpServlet {
15     private static final long serialVersionUID = 1L;
16        
17     /**
18      * @see HttpServlet#HttpServlet()
19      */
20     public AjaxServlet() {
21         super();
22         // TODO Auto-generated constructor stub
23     }
24 
25     /**
26      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
27      */
28     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29         // TODO Auto-generated method stub
30         
31         //response.getWriter().write("zhangsan");
32         
33                 try {
34                     //睡眠5秒 可以看出异步与同步的区别
35                     Thread.sleep(5000);
36                 } catch (InterruptedException e) {
37                     e.printStackTrace();
38                 }
39                 
40                 String parameter = request.getParameter("name");
41                 
42                 response.getWriter().write(Math.random()+parameter);
43         
44     }
45 
46     /**
47      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
48      */
49     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
50         // TODO Auto-generated method stub
51         doGet(request, response);
52     }
53 
54 }
ajaxServlet

 

Jquery 的Ajax 技术:

jquery 是一个js框架,自然对js原生的ajax 进行了封装,封装后的ajax 操作方法更简洁,功能更强大,

常用的有三种方式:

1.$.get(url,[data],[callback],[type])

2$.post(url,[data],[callback],[type])

其中:

url:代表请求的服务器端地址

data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)

callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)

type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)

常用的返回类型:text、json、html等

3. $.ajax({option1:value,opiton2:value2...})

常用的option有如下:

async:是否异步,默认是true代表异步

data:发送到服务器的参数,建议使用json格式

dataType:服务器端返回的数据类型,常用text和json

success:成功响应执行的函数,对应的类型是function类型

type:请求方式,POST/GET

url:请求服务器端地址

 

示例代码:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 <script type="text/javascript" src="js/jquery.min.js"></script>
 7 <script type="text/javascript">
 8 
 9 
10     function fn1(){
11         //get异步访问
12         $.get(
13             "ajaxServlet01", //url地址
14             {"name":"张三","age":25}, //请求参数
15             function(data){ //执行成功后的回调函数
16                 //{\"name\":\"tom\",\"age\":21}
17                 alert(data.name);
18             },
19             "json"
20         );
21     }
22     function fn2(){
23         //post异步访问
24         $.post(
25             "ajaxServlet01", //url地址
26             {"name":"李四","age":25}, //请求参数
27             function(data){ //执行成功后的回调函数
28                 alert(data.name);
29             },
30             "json"
31         );
32     }
33     
34     
35     function fn3(){
36         $.ajax({
37             //url 地址
38             url:"ajaxServlet01",
39             //是否异步 默认为异步
40             async:true,
41             //请求方式,POST/GET
42             type:"POST",
43             //发送到服务器的参数,建议使用json格式
44             data:{"name":"lucy","age":18},
45             //成功响应执行的函数,对应的类型是function类型
46             success:function(data){
47                 alert(data.name);
48             },
49             //错误响应执行的函数,对应的类型是function类型
50             error:function(){
51                 alert("请求失败");
52             },
53             //服务器端返回的数据类型,常用text和json
54             dataType:"json"
55         });
56     }
57 </script>
58 
59 </head>
60 <body>
61     <input type="button" value="get访问服务器端" onclick="fn1()"><span id="span1"></span>
62     <br>
63     <input type="button" value="post访问服务器端" onclick="fn2()"><span id="span2"></span>
64     <br>
65     <input type="button" value="ajax访问服务器端" onclick="fn3()"><span id="span2"></span>
66     <br>
67 </body>
68 </html>
jquery 的ajax 方法
 1 package com;
 2 
 3 import java.io.IOException;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 /**
11  * Servlet implementation class AjaxServlet01
12  */
13 @WebServlet("/ajaxServlet01")
14 public class AjaxServlet01 extends HttpServlet {
15     private static final long serialVersionUID = 1L;
16        
17     /**
18      * @see HttpServlet#HttpServlet()
19      */
20     public AjaxServlet01() {
21         super();
22         // TODO Auto-generated constructor stub
23     }
24 
25     /**
26      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
27      */
28     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29         // TODO Auto-generated method stub
30         request.setCharacterEncoding("UTF-8");
31         
32         String name = request.getParameter("name");
33         String age = request.getParameter("age");
34         
35         System.out.println(name+"  "+age);
36         
37         
38         //java代码只能返回一个json格式的字符串  编码格式 避免乱码
39         response.setContentType("text/html;charset=UTF-8");
40         //传递json的方式要特别记录一下  要添加下划线
41         //传递成功返回的json 类型数据
42         response.getWriter().write("{\"name\":\"汤姆\",\"age\":21}");
43         
44     }
45 
46     /**
47      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
48      */
49     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
50         // TODO Auto-generated method stub
51         doGet(request, response);
52     }
53 
54 }
ajaxServlet

 

json 格式:

1.对象格式: {"key":obj,"key2":obj,....}

2.数组格式:[obj,obj,obj....]

  1 1.
  2 <script language="JavaScript">
  3     /**
  4      * 案例一 
  5      *  {key:value,key:value}
  6      *  
  7      * class Person{
  8      *       String firstname = "张";
  9      *    String lastname = "三丰";
 10      *    Integer age = 100;
 11      * }
 12      * 
 13      * Person p = new Person();
 14      * System.out.println(p.firstname);
 15      */
 16     
 17     var person = {"firstname":"张","lastname":"三丰","age":100};
 18      
 19      //取出lastname
 20      alert(person.lastname);
 21      //取出age
 22      alert(person.age);
 23     
 24     
 25 
 26   </script>
 27 
 28 
 29 
 30 2.
 31 
 32   <script language="JavaScript">
 33       /**
 34      * 案例二
 35      *  [{key:value,key:value},{key:value,key:value}]
 36      *  
 37      */
 38      
 39      var persons = [
 40                         {"firstname":"张","lastname":"三丰","age":100},
 41                         {"firstname":"李","lastname":"四","age":25}
 42                     ];
 43      
 44     //取出 firstname=李
 45     alert(persons[1].firstname);
 46     //取100
 47     alert(persons[0].age);
 48       
 49       
 50   </script>
 51 
 52 3.
 53 
 54 <script language="JavaScript">
 55    /**
 56      * 案例三
 57      * {
 58      *   "param":[{key:value,key:value},{key:value,key:value}]
 59      * }
 60      *  
 61      *  
 62      */
 63      
 64      var json = {
 65                      "baobao":[
 66                                    {"name":"小双","age":28,"addr":"扬州"},
 67                                    {"name":"建宁","age":18,"addr":"紫禁城"},
 68                                    {"name":"阿珂","age":10,"addr":"山西"},
 69                                ]
 70                  };
 71     
 72      //娶name = 建宁
 73      alert(json.baobao[1].name);
 74      
 75      //取addr 山西
 76      alert(json.baobao[2].addr);
 77     
 78     
 79   </script>
 80 
 81 4.
 82 
 83 <script language="JavaScript">
 84    /**
 85      * 案例四
 86      * {
 87      *   "param1":[{key:value,key:value},{key:value,key:value}],
 88      *   "param2":[{key:value,key:value},{key:value,key:value}],
 89      *   "param3":[{key:value,key:value},{key:value,key:value}]
 90      * }
 91      *  
 92      *  
 93      */
 94      var json = {
 95                      "baobao":[
 96                                    {"name":"小双","age":28,"addr":"扬州"},
 97                                    {"name":"建宁","age":18,"addr":"紫禁城"},
 98                                    {"name":"阿珂","age":10,"addr":"山西"},
 99                                ],
100                       "haohao":[
101                                    {"name":"张爽","age":25,"addr":"吉林"},
102                                    {"name":"舒洁","age":23,"addr":"赤峰"}
103                                ]
104                  };
105      
106     alert(json.haohao[1].name);
107      
108 
109   </script>
110 
111 
112 5.
113 <script language="JavaScript">
114      /**
115      * 案例五
116      * {
117      *   "param1":"value1",
118      *   "param2":{},
119      *   "param3":[{key:value,key:value},{key:value,key:value}]
120      * }
121      *  
122      *  
123      */
124      
125      var json = {
126             "key1":"value1",
127             "key2":{"firstname":"张","lastname":"三丰","age":100},
128             "key3":[
129                        {"name":"小双","age":28,"addr":"扬州"},
130                        {"name":"建宁","age":18,"addr":"紫禁城"},
131                        {"name":"阿珂","age":10,"addr":"山西"},
132                    ]
133      };
134      
135      alert(json.key2.lastname);
136      
137      alert(json.key3[2].name);
138      
139      
140   </script>
View Code

 

json 插件的转换

将java的对象或集合转成json形式字符串

 

json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。

常用的json转换工具有如下几种:

1)jsonlib

2)Gson:google

3)fastjson:阿里巴巴

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!