JS DOM中Ajax的使用
一、概念
全称:Asynchronors Javascript XML 异步JS数据交换格式。
【Asynchronous】:异步的,即在执? AJAX 请求时不会阻塞后?代码的运?。
【JavaScript】:使? JavaScript 实现浏览器与服务器之间的数据交互。
【XML】:?种数据结构,AJAX 创建之初在与服务器进?数据交换时,使?的数据结构就是 XML。但是现在已经慢慢被 JSON 数据结构所取代。
二、步骤
1. 创建 XMLHttpRequest 对象。
//1、:创建 XMLHttpRequest 对象。 let xhr = new XMLHttpRequest();
考虑到浏览器版本的不同,做出简单的判断
let xhr;
if(window.XMLHttpRequest){
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执?代码
xhr = new XMLHttpRequest();
} else {
// IE6, IE5 浏览器执?代码
xhr = new ActiveXObject( ‘Microsoft.XMLHTTP‘ );
} 2. 打开连接。
格式:
xhr.open(method, url, async); /** *method:数据接收方式,GET/POST *url:数据链接,JSON格式 *async:是否异步,JS的特性本身为异步,所以通常设为默认值“true” */
例子:
xhr.open("get", "https://getman.cn/mock/getStudents/data.json", true); 3. 发送 HTTP 请求。
xhr.send();
若为GET方式传输,则不用填参数,若为POST请求,传递的数据是放在 send ?法的参数中。
xhr.send("username=zhangsan&pwd=123");4. 处理服务器返回的消息,实现局部刷新。
xhr.onreadystatechange = function(){
let text = xhr.responseText;
console.log( text );
} 状态值 readyState 都会发?改变
0:请求未初始化,即还没有调? send ?法;
1:服务器连接已建?,即已调? send ?法,正在发送请求;
2:请求已接收,即 send ?法执?完成;
3:请求处理中,即正在解析响应内容;
4:请求已完成,且响应已就绪,即响应内容解析完成,可以在客户端进?调?了;=>只有当状态值为 4 时,才表示请求完成
请求完成后,判断请求状态,状态码 status 为 200 时表示请求成功
完整代码:
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
let text = xhr.responseText;
console.log( text );
}
}三、封装自己的Ajax
AJAX 的操作是?种固定的模式,这让我们想到,是否能够将其操作流程封装,让我们在以后
的使?过程中更加?便。
function ajax({
url,
success,
data = {},
type = "get",
async = true
}) {
let xhr;
//1、:创建 XMLHttpRequest 对象。
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、3、:打开连接。发送 HTTP 请求。(根据类型是 get 或者 post 来决定数据 data 不同的发送? 式)
if ((type = type.toUpperCase()) == ‘GET‘) {
xhr.open(‘get‘, url + ‘?‘ + jsonToString(data), true);
xhr.send();
} else{
xhr.open(‘post‘, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded "); //?般数据都以该?式传输
xhr.send(jsonToString(data));
}
//4、:处理服务器返回的消息,实现局部刷新。
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
let data = xhr.responseText
success(data);
// console.log(data);
} else {
// error && error();
}
};
};
//?来将数据由json对象转换成符合url查询部分格式的字符串,?便数据的传输
function jsonToString(json) {
var arr = [];
for (var i in json) {
arr.push(i + ‘=‘ + json[i]);
};
return arr.join(‘&‘);
}
}