Ajax(XMLHttpRequest对象)
let xml = new XMLHttpRequest() | new ActiveXObject("Miscrosoft.XMLHTTP") //创建XMLHttpRequest()对象
//get
xml.open('get','/login?name=lisi&pass=123456',true) //true 是异步 false 是同步
xml.send()
//post
xml.open('post','/login',true)
xml.setRequestHeader('Content-type","application/x-www-form-urlencoded")
xml.send("name=lisi&pass=123456")
xml.onreadystatechange = function () {
if(xml.readyState == 4) { // readyState == 4 说明请求已经发送完成
0:未初始化。尚未调用open()方法。
1:启动。已经调用open()方法,但尚未调用send()方法。
2:发送。已经调用send()方法,但尚未收到响应。
3:接收。已经接收到部分响应数据。
4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了。
if(xml.status == 200){
alert(xml.responseText)
}
}
}
//封装
ajax({
type: 'post/get',
url: ' ',
data: ' ',
dataType: ' ',
success (res)=>{},
error() => {}
})
function ajax (){
let ajax = {
type: arguments[0].type || 'GET',
url:arguments[0].url || ''",
data:arguments[0] || null,
async:arguments[0].asunc || 'true',
dataType: arguments[0].dataType || 'text',
contentType: arguments[0].contentType || "application/x-www-form-urlencded",
beforeSend: arguments[0].beforeSend || function (){},
success:argument[0].success || function () {},
error:arguments[0].erroe || function () {}
}
ajax.beforeSend();
xml.open(ajax.type',ajax.url,ajax,async);
xml.sendRequestHeader('Content-type',ajax.contentType);
xml.send(ajax.data);
xml.onreadstatechange = function () {
if(xml.readyState == 4) {
if(xml.status == 200) {
ajax.success(xml.response)
}else{
ajax.error()
}
}
}
}
//仅供参考 菜鸟一枚 参考了其他人的代码敲的

浙公网安备 33010602011771号