Ajax 是异步的xml 和javascript,是一种综合技术。
利用 XMLHttpRequest(xhr)和后端进行数据交换。通过js 动态的渲染页面实现网页异步局部更新
同步与异步
同步代码会按顺序执行,当前面代码未执行完毕,后续代码不会执行,会阻塞代码执行异步不会阻塞代码
XMLHttpRequest(xhr)
创建xml对象
var xhr = new XMLHttpRequest();
打开HTTP连接
xhr.open(method,url,aync=true)
监听xhr的变化
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");
}
}
XHR
open()send()setRequestheader()xhr.readystate
0,'未初始化...'
1,'请求参数已准备,尚未发送请求...'
2,'已经发送请求,尚未接收响应'
3,'正在接受部分响应...'
4,'响应全部接受完毕'
响应内容
response 响应内容
responseText 响应文本内容
responseXML 响应xml内容
status 响应码 200代表成功statusText 响应的文本 ok代表成功
ajax优缺点
优点
不刷新更新页面,提升用户体验异步的提升页面的加载速度减轻服务器压力,实现浏览器端渲染
缺点
对搜索引擎不友好
文件上传
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);
ajax jQuery
$.ajax()$.get()$.post()第三层----
elem.load(xxx)加载xxx内容到elem元素;$.getScript(xxx)加载xxxscript文件 执行js;$.getJson(xxx)加载xxxjson文件
所有的jQuery ajax方法都支持三种写法
回调函数
$.getJSON(url,function(response,status,xhr){
//url请求的地址
//funcrion请求成功回调函数
//response 请求响应的数据
//status "success"
//xhr jquery的promise对象
})
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对象
.then() .catch().done() .fail() .always()status状态 200 statusText OK readyState 4
全局ajax事件(加载提示)
//开始ajax
$(doxument).ajaxStart(function(e){})
//停止ajax
$(doxument).ajaxStop(function(e){})
$.ajax({})
url 请求的地址method 请求的方法 GET|POSTdataType 返回数据类型 json jsonp textjsonp 跨域回调方法默认 callbacksuccess 成功 error 失败done 完成 fail失败beforeSend 发送前compelete ajax完毕Content-Type:“application/x-www-from-urlencoded”
fetch
get
fetch(url)
.then(res=>res.json())
.then(res=>{
console.log(res)
})
post
fetch(url,{
method:"POST",
body:"name=leh&age=23",
headers:{'Content-Type':'application/x-www-from-urlencoded'}
})
.then(res=>)
.catch(err=>)
jQuery优化
缓存dom多使用正确的选择器
原生 # id tag class子选择 find children
使用min.js使用 事件$(‘ul’).on(‘click’,‘li’,function(){}) 事件的target 事件冒泡