1.new一个XMLHttpRequest对象
const requert = new XMLHttpRequest
2.设置open()请求方式
requert.open('get','text.html',true)
3.send()发送请求
// get 不需要传递参数
// post 需要传递参数 requert.send("name=jay&age=18")
requert.send(null)
4.监听onreadystatechange请求状态
5.接收返回数据
源代码:
var xmlHttpRequest;
//创建xmlhttprequest对象
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {//其他浏览器什么火狐、谷歌等等
xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {//判断是否是IE浏览器
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
}
//响应HTTP请求状态变化的函数
function httpStateChange() {
//判断异步调用是否完成
if (xmlHttpRequest.readyState == 4) {
//判断异步调用是否成功,如果成功开始局部更新数据
if (xmlHttpRequest.status == 200 || xmlHttpRequest.status == 0) {
//查找节点
var node = document.getElementById("myDIv");
//更新数据
node.firstChild.nodeValue = xmlHttpRequest.responseText;
}
else {
//如果异步调用未成功,弹出警告框,并显示出错信息
alert("异步调用出错/n返回的HTTP状态码为:" + xmlHttpRequest.status
+ "/n返回的HTTP状态信息为:" + xmlHttpRequest.statusText);
}
}
}
//异步调用服务器段数据
function getData(name, value) {
//创建XMLHttpRequest对象
createXMLHttpRequest();
if (xmlHttpRequest != null) {
//创建HTTP请求
xmlHttpRequest.open("get", "/ajax.json", true)
//设置HTTP请求状态变化的函数
xmlHttpRequest.onreadystatechange = httpStateChange;
//发送请求
xmlHttpRequest.send();
}
}