Ajax 是异步的xml 和javascript,是一种综合技术。
利用 XMLHttpRequest(xhr)和后端进行数据交换。通过js 动态的渲染页面实现网页异步局部更新
var xhr = new XMLHttpRequest();
xhr.open(method,url,aync=true)
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText);
p.innerHTML = xhr.responseText;
}
}
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
GET
//建立一个xhr对象
var xhr = new XMLHttpRequest();
//打开的方法,地址,是否异步
xhr.open("GET","./be.txt",true);
xhr.send();//发送出去
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText,xhr);
//输出ajax返回的文本内容
p.innerHTML = xhr.responseText;
}/*如果xhr的状态是第4个状态,响应码为200*/
}//监听xhr的变化
POST
//建立一个xhr对象
var xhr = new XMLHttpRequest();
xhr.open("post","http://www.520mg.com/ajax/echo.php",true);
//设置头信息
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//发送http请求数据
xhr.send("name=mumu&age=18");
//监听
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText);
p.innerHTML = xhr.responseText;
console.log("ajax执行B");
}
}
0,'未初始化...'
1,'请求参数已准备,尚未发送请求...'
2,'已经发送请求,尚未接收响应'
3,'正在接受部分响应...'
4,'响应全部接受完毕'
response 响应内容
responseText 响应文本内容
responseXML 响应xml内容
优点
缺点
var xhr = new XMLHttpRequest();
//打开http连接
xhr.open("POST","https://www.520mg.com/ajax/file.php",true);
var data = file.files[0];//获取文件
var fdata = new FormData();
fdata.append("file",data);
//获取formData 要传递的表单文件
//监听xhr的加载事件
xhr.upload.onprogress = function(e){
// console.log(e);
//监听上传文件的进度
console.log(e.loaded,e.total,Math.round(e.loaded/e.total*100)+"%");
//e.loaded是已上传,e.total总文件大小
}
xhr.onload = function(){
console.log("json文件",xhr.responseText);
var res = JSON.parse(xhr.responseText);
//把json字符串转换为JavaScript对象
if(res.error==0){
var img = document.createElement("img");
img.src = "https://www.520mg.com"+res.pic;
img.width = 200;
box.appendChild(img);
}
}
xhr.send(fdata);
$.getJSON(url,function(response,status,xhr){
//url请求的地址
//funcrion请求成功回调函数
//response 请求响应的数据
//status "success"
//xhr jquery的promise对象
})
$.getJSON(url)
.then(res=>{})
.catch(err=>{})
$.getJSON(url)
.done(res=>{})
.fail(err=>{})
.always(res=>{})
$.get() $.post()
url:url,
data?(post中),
function(res,status,xhr){}
jquery ajax promise对象
//开始ajax
$(doxument).ajaxStart(function(e){})
//停止ajax
$(doxument).ajaxStop(function(e){})
fetch(url)
.then(res=>res.json())
.then(res=>{
console.log(res)
})
fetch(url,{
method:"POST",
body:"name=leh&age=23",
headers:{'Content-Type':'application/x-www-from-urlencoded'}
})
.then(res=>)
.catch(err=>)