1.ajax的工作原理
1)创建XMLHttpRequest()对象
2)设置请求方式, open()
3)调用回调函数onreadystatechange
4)发送请求,send()
ajax实现局部更新
<script>
// ajax实现局部更新
window.onload = function () {
//获取某一个元素事件
var btn = document.getElementById('Btn');
//点击事件发送ajax请求
btn.onclick = function () {
var xhr = null;
//1.判断兼容性,创建ajax对象
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
//兼容IE6以下版本
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.判断请求方式,设置请求方式,地址
if (method == 'get') {
//假设的地址和参数
xhr.open('get', 'url?name=' + 123, true);
xhr.send()
} else if (method == "post") {
xhr.open('post', url, true)
//设置表单提交时的内容类型
//Content‐type数据请求的格式,请求头地址
xhr.setRequestHeader(
"Content‐type",
"application/x‐www‐form‐urlencoded"
);
xhr.send('name=123')
}
//3.响应数据的回调函数onreadystatechange
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//完成时的状态码
if(xhr.status==200){//数据响应成功的代码
//返回以文本形式存放的内容
console.log(xhr.responseText);
}
}
}
}
}
</script>