AJAX初始使用方法

GET

1.创建

const xhr = new XMLHttpRequest()

兼容

const xhr = new ActiveXObject('Mscrosoft.XMLHTTP')

2.请求

xhr.open('GET','./Login.php?username=wzq&password=123'.,true)

3.发送

xhr.send()

4.获取

xhr.onreadystatechang = function (){

判断ajax的状态码

if(xhr.readyState === 4){

判断HTTP码

200-299

304无更新数据

if(xhr..status>=200&&xhr.status<300||xhr.status===304){

console.log(xhr.responseText)

}

}

}

POST

1.创建

const xhr = new XMLHttprRequest()

2.请求

xhr.open('POST','./login.php',true)

如果使用post必须设置请求头

xhr.setRequestHeader('content-type','application/x-www-form-url-encoded')

3.发送

xhr.send(`username=wzq&password=123`)

4.获取

xhr.onreadystatechang = function () {

判断AJAX的状态码

if(xhr.readyState === 4){

if(xhr.status >=200&&xhr.status <300||xhr.status===304){

console.log(xhr.responseText)

}

}

}

你可能感兴趣的:(AJAX初始使用方法)