1. AJAX
1.1 概念
ASynchronous JavaScript And XML 异步的JavaScript 和 XML
异步和同步:客户端和服务器端相互通信的基础上
异步:客户端必须等待服务器端的响应。在等待的期间客户端不能做其他操作
同步:客户端不需要等待服务器端的响应。在服务器处理请求的过程中,客户端可以进行其他的操作
Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新
这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
AJAX提升用户的体验
1.2 实现方式
原生的JS实现方式(了解)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","ajaxServlet?username=tom",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var responseText = xmlhttp.responseText; alert(responseText); } }
|
JQeury实现方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| * 语法:$.ajax({键值对}); $.ajax({ url:"ajaxServlet1111" , type:"POST" , data:{"username":"jack","age":23}, success:function (data) { alert(data); }, error:function () { alert("出错啦...") }, dataType:"text" });
|
1 2 3 4 5 6 7
| 发送get请求 * 语法:$.get(url, [data], [callback], [type]) * 参数: * url:请求路径 * data:请求参数 * callback:回调函数 * type:响应结果的类型
|
1 2 3 4 5 6 7
| 发送post请求 * 语法:$.post(url, [data], [callback], [type]) * 参数: * url:请求路径 * data:请求参数 * callback:回调函数 * type:响应结果的类型
|
Axios实现方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
1 2 3 4 5 6 7 8 9 10
| axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
2. JSON
2.1 概念
JavaScript Object Notation JavaScript对象表示法
- 进行数据的传输
- JSON 比 XML 更小、更快,更易解析
2.2语法
基本规则
- 数据在名称/值对中:json数据是由键值对构成的
- 键用引号(单双都行)引起来,也可以不使用引号
- 值得取值类型:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 数组(在方括号中) {“persons”:[{},{}]}
- 对象(在花括号中) {“address”:{“province”:”陕西”….}}
- null
- 数据由逗号分隔:多个键值对由逗号分隔
- 花括号保存对象:使用{}定义json 格式
- 方括号保存数组:[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var person = {"name": "张三", "age": 23, "gender": true}; var person ={ "persons":[ {"name": "张三", "age": 23, "gender": true}, {"name": "李四", "age": 24, "gender": true}, {"name": "王五", "age": 25, "gender": false} ] }; var ps = [{"name": "张三", "age": 23, "gender": true}, {"name": "李四", "age": 24, "gender": true}, {"name": "王五", "age": 25, "gender": false}];
|
获取数据:
- json对象.键名
- json对象[“键名”]
- 数组对象[索引]
- 遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| person.name; person["name"]
for (var i = 0; i < ps.length; i++) { var p = ps[i]; for(var key in p){ alert(key+":"+p[key]); } }
|