Ajax概述
它是浏览器提供的一套方法,可以实现页面无刷新更新数据,增强用户体验感,比如上拉显示更多内容,搜索框提示文字下拉列表,用户登录离开焦点验证表单等场景均用到了ajax技术
ajax的运行环境:需要运行在网站环境中
ajax的运行原理:
ajax相当于浏览器向服务器发送请求和接收响应的代理人,在不影响用户浏览页面的情况下,局部更新页面数据,提高用户体验。
Ajax基本实现步骤
<script>
// 实例化ajax对象
var xhr = new XMLHttpRequest();
// 配置ajax对象, 即设置访问方式和访问服务器的url
xhr.open('get', 'http://localhost:3000');
// 向服务器发送请求
xhr.send();
// onload事件 在接收完服务器的响应内容后触发
xhr.onload = function() {
console.log(xhr.responseText); // 获取服务器的响应内容
}
</script>
Json数据类型转换
通常,服务器的响应内容是json对象格式,在http请求与响应中,请求参数和响应内容都是字符串格式,这就需要json对象和字符串之间的转换
若服务器传来的响应内容是json对象的字符串,用**JSON.parse()**转换成json对象;
相反可以用**JSON.stringify()**方法将json对象转换成字符串
请求参数的传递
1. get请求参数: 拼接在url中传递
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:3000/get?name=zhangsan&age=20');
xhr.send();
xhr.onload = function() {
console.log(JSON.parse(xhr.responseText));
}
2. post请求参数:在请求报文中传递
设置请求报文头部的content-type属性,通过xhr.setRequestHeader()方法设置,也就是请求参数的格式,常用的有两种:
- 一是 name=zhangsan&age=20 这种以&符号拼接的字符串格式,content-type为:application/x-mmm-form-urlencoded
- 另一种是json对象的字符串格式,content-type为:application/json
将post请求参数作为shr.send()方法的参数进行传递
<script>
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/post');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('name=zhangsan&age=20');
xhr.onload = function() {
console.log(xhr.responseText);
}
</script>
<script>
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/post');
// 设置post请求参数格式为json对象格式
xhr.setRequestHeader('Content-Type', 'application/json');
var data = {
name: 'zhangsan',
age: 20
};
xhr.send(JSON.stringify(data)); // 请求参数必须以字符串的格式传递,需要将json对象转换成字符串
xhr.onload = function() {
console.log(xhr.responseText);
}
</script>
通过ajax状态码获取服务器响应内容
ajax状态码:
利用ajax状态码获取服务器响应内容
<script>
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:3000');
// 添加ajax状态码改变的事件
xhr.onreadystatechange = function() {
console.log(xhr.readyState);
// ajax状态码等于4说明已经获取到了服务器的响应内容
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
};
// 发送请求
xhr.send();
</script>
利用onload事件和onreadystatechange事件获取服务器响应内容的区别:
Ajax错误处理
通过xhr.status可以获取http的状态码,根据http的状态码可以判断错误类型,进行相应的处理
- xhr.status 为404:网络通畅,服务器找不到所请求的路由,检查请求地址是否出错
- xhr.status 为500:网络通畅,服务器端错误,检查服务器端代码是否出错
- 网络中断,会触发xhr.onerror事件,在事件处理函数中可以进行相应处理
低版本IE浏览器的缓存问题
Ajax函数封装
可以将ajax向服务器发送请求的代码封装到一个函数中,之后发送请求只需调用该函数即可,减少代码冗余和重复
function ajax (options) {
// 存储的是默认值
var defaults = {
type: 'get',
url: '',
data: {
}