目录
一、解决的问题
在不刷新网页的情况下去更新数据
二、核心知识
1、兼容写法
if(window.ActiveXObject){ ajax = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ ajax = new XMLHttpRequest(); }
2、IE6不兼容 XMLHttpRequest
三、具体步骤
1、创建XMLHttpRequest对象
xmlhttprequest对象用来和服务器交换数据
var ajax = new XMLHttpRequest()
2、创建HTTP请求(打开)
async参数为true(代表异步)或者false(代表同步)
(1)同步:上一个任务结束下一个在开始(eg:alert弹窗,登陆注册流程)
ajax.open("get","xxx.php",false);
注意:此处参数2为服务器地址,参数3为是否异步操作
ajax.open("post",xxx.php,false);
此处用到 ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
(2)异步:按顺序开始不一定按顺序结束(eg:图片加载,上传下载等任务)
ajax.open("get","xx.php",true)
ajax.open("post",xxx.php,true)
此处用到 ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
发送后状态值 readystate的变化:
<1>0:对象已建立,还未初始化,未调用send
<2>1:open已调用,未调用send
<3>2:send已调用,其它未知
<4>3:请求已发送,正在接收数据
<5>4:表示数据已经收到
3、服务器响应(监听)
使用xmlhttprequest对象的responsetext或responsexml属性获得服务器的响应
ajax.onreadystatechange = function(){ console.log(ajax.responseText); }
4、发送请求
onreadystatechange函数,当发送请求到服务器,我们想要服务器响应执行一些功能就需要使用onreadystatechange函数,每次xmlhttprequest对象的readystate发生改变都会触发onreadystatechange函数
ajax.send(null)
发送后返回四种参数:
<1>responseText:作为响应的主体返回的文本
<2>responseXML
<3>status
1)200:成功
2)202:请求接受,处理未完成
3)400:语法错误
4)404:找不到指定url
5)500:内部服务器错误
<4>statusText:跨浏览器时可能不太一致
具体代码:
// 1. 原生AJAX
// 创建ajax 4步
// 1.1 新建
var xhr = new XMLHttpRequest();
// 1.2 配置
// xhr.open(请求方式,请求地址,是否异步);
var url = ('http://jsonplaceholder.typicode.com/posts');
xhr.open('get',url,false);
// 1.3 响应
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if(xhr.readyState === 4){
console.log(xhr.responseText);
// // 数据渲染
var arr = JSON.parse(xhr.responseText);
arr.forEach(function(item){
var h3 = document.createElement("h3");
h3.innerHTML = item.title;
var p = document.createElement("p");
p.innerHTML = item.body;
document.body.appendChild(h3);
document.body.appendChild(p);
})
}
// }
// 1.4 发送
xhr.send();
console.log(123123);