ajax是一种能够实现局部网页刷新的技术,可以使网页异步刷新。
ajax的实现主要包括四个步骤:
1、 创建核心对象XMLhttpRequest;
2、 利用open方法打开与服务器的连接;
3、 利用send方法发送请求;("POST”请求时,还需额外设置请求头)
4、 监听服务器响应,接收返回值。
//1-创建核心对象
//该对象有兼容问题,低版本浏览器应使用ActiveXObject
const xthhp = new XMLHttpRequest();
//2-连接服务器
//open(method,url,async)
xhttp. open("POST", "http://localhost:3000", true)
〃设置请求头
xmlHttp. setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//3-发送请求
//send方法发送请求参数,如为GET方法,则在open中url后拼接
xhttp. send({
_id: 123
})
〃4-接收服务器响应
//onreadys tat echange事件,会在xhttp的状态发生变化时自动调用
xhttp. onreadystatechange = function() {
//状态码共5种:0-未open 1-已open 2-已send 3-读取响应 4-响应读取结束
if (xhttp. readyState = 4 && xhttp.status = 200) {
alert ("ajax请求已完成")
}
Was this helpful?
0 / 0