1.什么是ajax?
是通过js已异步的形式操作json
2.ajax的步骤?
1.要有浏览器
2.创建xhr对象
3.xhr.open(请求方式,请求地址,boolean|true 异步|false 同步);
4.xhr.send();//get请求里面不许传参和post请求里面需要传参
5.xhr.onreadystatechange 监测0-1,1-2,2-3,3-4 会执行四次。
通过xhr.readyState来判断当前状态
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
6. 通过xhr.status来获取服务器返回的状态码,做相应的操作。
3.封装一个ajax兼容性方法:
<script>
function ajaxFunc(method,url,data,callback,flag){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject('Miscrosoft.XMLHttp');
}
if(method == 'GET'){
xhr.open(method,url+data,flag);
xhr.send()
}else if(method == 'POST'){
xhr.open(method,url,flag);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
xhr.send(data);
}
// xhr.open('GET','./getNews.php?username=tac&age=18',true);
// xhr.send();
// xhr.open('POST','./getNews.php',true);
// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
// xhr.send('username=tac&age=18');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status == 200){
callback(xhr.responseText)
// console.log(JSON.parse(xhr.responseText));
}
}
}
}
</script>