-
ajax:简单的说是异步的的js和XML,在无需刷新页面的同时,可以更新页面数据。
-
优势:
无需刷新页面更新数据
实现前后端负载平衡
异步与服务器通信 -
缺点:不利于浏览器引擎优化
-
使用ajax注意的问题:
缓存问题:?t=new date( ).getTime( );
乱码的问题:统一字符集 -
ajax原理:
首先创建一个XMLHttpRequest对象,通过这个对象的open方法与服务器建立链接,病将请求用send方法发送给服务器,随后通过事件监听,如果服务器找到请求的数据通过回电函数返回。 -
ajax同步异步的区别:
同步就相当于客户端发送请求给服务端,在等待服务端响应的请求时,客户端不做其他事情,当服务端做完了才返回客户端,这样客户端要一直等,用户体验不好。
异步就是当客户端发送请求给服务端时,在等待服务端响应的时候,客户端可以先做其他事情,节约了时间,提高了效率。 -
ajax的封装(get 和 post )
let ajax = {
get(url, fn) {
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState = 4) {
if (xhr.status === 200) {
if (typeof fn === 'function') {
fn(xhr.responseText);
}
}
}
}
},
post(url, data, fn) {
let xhr = window.XMLDocument ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.setRequestHeader('Content-type', 'Application/x-www-form-urlencoded;charset=utf-8');
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (typeof fn === 'function') {
fn(xhr.responseText);
}
}
}
}
}
}
- 使用promise封装ajax
function ajax(url){
let xhr = new XMLHttpRequest();
xhr.open('get',url,true);
xhr.send();
return new Promise((resolve,reject) => {
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
resolve(xhr.responseText);
}else{
reject();
}
}
}
})
}
- 简单的ajax
function ajax(url, fnWin, fnFaild) {
//创建XMLHttpRequest
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//open方法
xhr.open('GET', url, true);
//send方法
xhr.send();
//等待响应
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (fnWin instanceof Function) {
fnWin(xhr.responseText);
}
} else {
if (fnFaild instanceof Function) {
fnFaild();
}
}
}
}
}
5372

被折叠的 条评论
为什么被折叠?



