1. AJAX的代码怎么写:
AJAX的简易代码如下:
//创建请求
const xhr = new XMLHttpRequest();
//初始化请求
xhr.open('GET', '/xxx');
//监听请求
xhr.onerror = () => {
console.log('请求失败,失败的原因是:' + xhr.status);
}
xhr.onload = () => {
console.log('请求成功, 得到的内容是:' + xhr.responseText);
}
//发送请求
xhr.send();
AJAX的详细代码如下:
//创建请求
const xhr = new XMLHttpRequest();
//初始化请求
xhr.open('GET', '/xxx');
//监听请求
xhr.onreadystatechange = () => {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
console.log('请求成功,得到的内容是:' + xhr.responseText);
}else if(xhr.status >= 400) {
console.log('请求失败,状态码为:' + xhr.status);
}
}
}
//发送请求
xhr.send();
封装AJAX:
const ajax = ({ method, url, body, success, fail }) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log("请求成功,得到内容为:" + xhr.responseText);
success(xhr);
} else if (xhr.status >= 400) {
console.log("请求失败,状态码为:" + xhr.status);
fail(xhr);
}
}
};
xhr.send(body);
return {
/* api */
};
};
2. AJAX的优缺点:
优点:可以请求任意内容;不用刷新页面。
缺点:代码难记。