一、手写AJAX的步骤
node 运行npm install jquery -s安装-s创建和发布都要用dependencies -d只在创建使用上线后不用
- 创建XMLHttpRequest对象
- 指定响应函数
- 打开连接(指定请求)
- 发送请求
- 创建响应函数
注:第三步是使用XMLHttpRequest对象的open()方法,字面意思open是打开的意思,即打开连接。但是准确的说应该是指定Http请求。因为浏览器在使用AJAX技术与服务通信时,发送的是Http请求,那么就要指定Http的请求方法,url等信息。
var xmlhttp=null;//声明一个变量,用来实例化XMLHttpRequest对象
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();// 新版本的浏览器可以直接创建XMLHttpRequest对象
}
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// IE5或IE6没有XMLHttpRequest对象,而是用的ActiveXObject对象
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;//指定响应函数为state_Change
xmlhttp.open("GET","/example/xdom/note.xml",true);//指定请求,这里要访问在/example/xdom路径下的note.xml文件,true代表的使用的是异步请求
xmlhttp.send(null);//发送请求
}
else
{
alert("Your browser does not support XMLHTTP.");
}
//创建具体的响应函数state_Change
function state_Change()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
// 这里应该是函数具体的逻辑
}
else
{
alert("Problem retrieving XML data");
}
}
}
二、promise封装ajax
//创建promise对象
const p = new Promise((resolve, reject) => {
//创建XMLHttpRequest对象
const xhr = new XMLHttpRequest;
//初始化
xhr.open('GET', 'http://127.0.0.1/api/get');
//发送
xhr.send();
//处理响应信息
xhr.onreadystatechange = function () {
//0 UNSENT 代理被创建,但尚未调用 open() 方法。
// 1 OPENED open()方法已经被调用。
// 2 HEADERS_RECEIVED send()方法已经被调用,并且头部和状态已经可获得。
// 3 LOADING 下载中; 属性已经包含部分数据。responseText
// 4 DONE 下载操作已完成。
if (xhr.readyState == 4) {