ajax2.0比ajax1.0:
1.formData: 控制提交数据、文件上传,服务器那边跟普通<form>一样的
2.cors跨域:请求头多了 origin,响应头带上Access-Control-Allow-Origin: 域名||*
formdata
set(key, value) 会覆盖
append(key, value) 不覆盖,可提交数组对象
get(key)=>value
delete(key)
let data=new FormData();
data.set('user', 'blue');
data.append('user', 'blue2');
console.log(data.getAll('user'));
原生Ajax
window.onload=function (){
let oBtn=document.getElementById('btn1');
oBtn.onclick=function (){
//1.创建 XMLHttpRequest 对象
let xhr=new XMLHttpRequest();
//2.连接
//true-异步,false-同步
xhr.open('GET', '1.php?a=12&b=5', true);
//3.发送
xhr.send();
//4.接收
xhr.onreadystatechange=function (){ //当 readyState 属性改变时,就会调用该函数。
/*0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪*/
if(xhr.readyState==4){
//成功:2xx、304
if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
alert('成功'+xhr.responseText);
}else{
alert('失败');
}
}
};
};
};
网友评论