AJAX
ajax想要实现浏览器与服务器之间的异步通信,需要使用XMLHttpRequest构造函数来实现
1.ajax使用步骤
//创建实例对象
conat xhr = new XMLHttpRequest();
//准备发送请求
xhr.open('POST','http:localhost.8080',true);
//发送请求,调用sand()发送请求
send();
//监听事件,处理响应。当接收到响应时触发readystatechange
//readystatechange事件一共有5个状态,可以通过readyState监听
//0:未初始化,未调用open()
//1:启动,已调用open(),但未调用send()
//2:发送,已经调用send()但并没有接受到响应
//3:接收,已接收到部分数据
//4:完成,已经接收到全部数据
xhr.onreadystatechange=()=>{
if(xhr.readyState!==4) return;
//判断http状态
if((xhr.status>=200&&xhr.status<300 )||xhr.status===304){
console.log(xhr.responseText)
console.log('数据正常使用!')
}else{
//其他处理
}
}
2.完成Ajax前后端通信
const xhr = new XMLHttpRequest();
xhr.onreadystatechange= () =>{
if(xhr.readyState !== 4) return;
if ((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304) {
console.log(xhr.responseText);
}
}
xhr.open('GET',url,true);
xhr.send(null);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。