版权声明:QAQ https://blog.csdn.net/mineblogjw/article/details/81945984
//1.创建xhr对象
var xhr;
if(window.XMLHttpRequest){
xhr = XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); //低版本 ie5-6 兼容处理
}
//2.注册回调函数--事件处理程序
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
... //相干什么就干什么吧
}
}
//readyState: 0-未初始化
1-读取中
2-已读取
3-交互中
4-完成
//3.向服务器发起连接:参数:请求方法,请求地址
xhr.open("get","/checkuser.do?username="+username); //get
xhr.open("post","/checkuser.do"); //post
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //post请求头
//4.传参
xhr.send(null); //get 地址传参了,这里不需要传
xhr.send("usernae="+username) //post
自己尝试着玩封装了一个ajax(调用传参method,url,params,callback,async就行了):
var xhr;
if(window.XMLHttpRequest){
xhr = XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function myAjax(method,url,params,callback,async){
if(async == undefined){
async = true;
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
callback();
}
}
}
if(method == "get"){
xhr.open(method,url+"?"+params,async);
}else if(method == "post"){
xhr.open(method ,url,async); //post
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(params);
}
//async:true--异步--默认方法--多线程同时做
:false--同步--单线程一件一件来
因为window.onload不支持异步,所以在window.onload中发起ajax的话要设置成同步
然后jq也有自己的ajax封装方法:
$.ajax({
type:"", //get,post
url:"", //......do
data:$("#id").serialize, //表单序列化,多个参数可以写成对象
success:function(data){
//执行成功回调函数 函数体
},
async:true
})