ajax

    技术2022-07-11  84

    什么是ajax

    Asynchronous Javascript And XML

    ajax异步的xml和JavaScript,是一种综合技术利用XMLHttpRequest和服务器进行数据交换通过js动态的渲染页面实现网页异步局部更新

    同步与异步

    同步:代码按顺序从上至下执行 会阻塞代码(alert)异步:异步不会阻塞代码执行 //同步 console.log("abc") alert("hhh") console.log("ddd") //异步 btn.onclick=function(){ console.log("A") var xhr=new XMLHttpRequest(); //打开http链接 xhr.open("POST","http://www.xxx.com/ajax/echo.php",true) //设置头信息 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log("B") px.innerHTML=xhr.responseText } } console.log("C") xhr.send("name=hh&age=30"); }

    输出:A C B

    步骤

    创建xml对象 var xhr=new XMLHttpRequest();打开http链接 xhr.open(打开方法 ,地址 , 是否异步)监听xhr变化 xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log(xhr.responseText,xhr) } } 设置头信息 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') 发送数据 xhr.send()

    xhr

    open()send()setRequestHeaderreadyState '0’未初始化‘1’ 请求参数已准备,尚未发送请求‘2’ 已经发送请求 尚未接收响应‘3’ 正在接受部分响应‘4’ 响应全部接受完毕 status 响应码 200 成功staticText 响应状态 okresponseText 响应文本形式

    ajax 优点

    不刷新更新页面 提升用户体验异步的提升页面的加载速度减轻服务器压力,实现浏览器渲染

    ajax缺点

    对搜索引擎不友好

    小例子

    使用get方法 新建xhr.html页面新建be.text文件xhr.html 获取be.text文件中的内容 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <button type="button" id="btn">加载</button> <p id="px"></p> </body> <script> // Asynchronous Javascript And XML // ajax异步的xml和JavaScript,是一种综合技术 // 利用XMLHttpRequest和后端进行数据交换 // 通过js动态的渲染页面实训网页异步局部更新 //单击按钮加载内容 btn.onclick=function(){ var xhr=new XMLHttpRequest();//建立xhr对象 xhr.open("GET","./be.text",true) //参数 打开方法 地址 是否异步 xhr.send();//发送出去 //监听xhr变化 xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ //如果xhr的状态是第四个状态,响应码为200 console.log(xhr.responseText,xhr) px.innerHTML=xhr.responseText } } } </script> </html>

    POST方法 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1 id="px"></h1> <button id="btn">加载</button> </body> <script type="text/javascript"> btn.onclick=function(){ var xhr=new XMLHttpRequest(); //打开http链接 xhr.open("POST","http://www.xxxx.com/ajax/echo.php",true) //设置头信息 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') xhr.send("name=hh&age=30"); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ console.log(xhr.responseText) px.innerHTML=xhr.responseText } } } </script> </html>

    小案例–文件上传

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <input type="file" id="file"/> <button id="btn">提交</button> </body> <script type="text/javascript"> btn.onclick=function(){ var xhr=new XMLHttpRequest(); xhr.open("POST","https://www.xxx.com/ajax/file.php",true) var data=file.files[0]; //获取FormData要传递的表单文件 var fdata=new FormData(); fdata.append("file",data); //监听上传进度 xhr.upload.onprogress=function(e){ console.log(e.loaded,e.total,Math.round(e.loaded/e.total*100)+"%") } //监听加载事件 xhr.onload=function(){ var res=JSON.parse(xhr.responseText) if(res.error==0){ var img=document.createElement("img"); img.src="https://www.xxx.com"+res.pic; img.width=100 document.body.append(img) } } xhr.send(fdata) } </script> </html>

    jQuery中的ajax

    总共分三层 最底层 $.ajax() 中间层 $.get() $.post() 最上层 $.getScript() $.getJson load()所有的jQuery ajax都有三种写法 如:$(function(){ $("button").click(function(){ //第一种 // $.getJSON("./be.json",function(res,status,xhr){ // console.log(res,status,xhr) // }) //第二种 // $.getJSON("./be.json") // .then(res=>console.log(res)) // .then(err=>console.log(err)) //第三种 $.getJSON("./be.json") .done(res=>{ console.log(res) }) .fail(xhr=>console.log("失败",xhr)) .always(res=>{ console.log("无论成功失败都执行",res) }) }) }) load() 加载xxx内容到elem元素 新建be.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p class="my">hello</p> <h1 id="h" style="color: red;">world</h1> </body> </html>

    新建jq.html

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="./js/jquery-3.4.1.js"></script> </head> <body> <div id="app"></div> <button>加载</button> </body> <script> $(function(){ $("button").click(function(){ $("#app").load("be.html .my") //加载be.html中的内容到div中,第二个参数可以指定加载的内容 }) }) </script> </html> $.getScript() 加载.js文件 执行js 新建 text.js alert("你好js")

    新建jq.html

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="./js/jquery-3.4.1.js"></script> </head> <body> <div id="app"></div> <button>加载</button> </body> <script> $(function(){ $("button").click(function(){ $.getScript("./test.js") }) }) }) </script> </html> $.getJSON() 新建be.json文件 {"name":"hh","age":"20"}

    新建jq.html

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="./js/jquery-3.4.1.js"></script> </head> <body> <div id="app"></div> <button>加载</button> </body> <script> $(function(){ $("button").click(function(){ // $.getJSON("./be.json",function(res,status,xhr){ // console.log(res,status,xhr) // }) // $.getJSON("./be.json") // .then(res=>console.log(res)) // .then(err=>console.log(err)) $.getJSON("./be.json") .done(res=>{ console.log(res) }) .fail(xhr=>console.log("失败",xhr)) .always(res=>{ console.log("无论成功失败都执行",res) }) }) }) </script> </html> $.get <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery-3.4.1.js"></script> </head> <body> <button type="button">加载</button> <p id="p"></p> </body> <script> //单击加载将be.text的内容放入p标签中 $(function(){ $("button").click(function(){ $.get("./be.text") .then(res=>{$("#p").text(res)}) }) }) </script> </html> $.post <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery-3.4.1.js"></script> </head> <body> <button type="button">加载</button> <p id="p"></p> </body> <script> $(function(){ $("button").click(function(){ $.post( "http://www.xxxx.com/ajax/echo.php", {name:"hhh",age:20}, // function(res,status,xhr){ // console.log(res,status,xhr) // } ) // .then(res=>{ // $("#p").text(res) // }) // .catch(err=>{console.log(err)}) .done(res=>{$("#p").text(res)}) .fail(err=>{console.log(err)}) .always(res=>{console.log(res)}) }) }) </script> </html> $.ajax <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery-3.4.1.js"></script> </head> <body> <button type="button">加载</button> <p id="p"></p> </body> <script> //单击加载将be.text的内容放入p标签中 $(function(){ $("button").click(function(){ // $.ajax({ // url:"be.text", // type:"GET", // success:function(res){ // console.log(res) // }, // fail:function(err){ // console.log(err) // } // }) $.ajax({ url:"http://www.520mg.com/ajax/echo.php", type:"POST", data:{name:"hh",age:18}, success:function(res){ console.log(res) }, fail:function(err){ console.log(err) }, beforeSend(arg){console.log("开始加载提示")}, completa(arg){console.log("关闭加载")} }) .then(res=>{console.log(res)}) .catch(err=>{console.log(err)}) // $.ajax({ // url:"https://wis.qq.com/weather/common?weather_type=observe|forecast_24h|air&source=pc", // dataType:"jsonp", // beforeSend(arg){console.log("开始加载提示")} // completa(arg){console.log("关闭加载")} // }) // .then(res=>{ // console.log(res) // }) // .catch(err=>{ // console.log(err) // }) }) // $(document).ajaxStart(function(e){ // console.log("全局开始") // }) // $(document).ajaxStop(function(e){ // console.log("全局结束") // }) }) </script> </html> fetch() <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <button type="button" id="btn">加载</button> </body> <script> // fetch 通过http管道方式访问服务器 btn.onclick=function(){ // fetch("./be.text") // .then(res=>res.text()) // .then(res=>{console.log(res)}) // .catch(err=>{console.log(err)}) // fetch("./be.json") // .then(res=>res.json()) // .then(res=>{console.log(res)}) // .catch(err=>{console.log(err)}) fetch("http://www.xxx.com/ajax/echo.php",{ method:"POST", body:"name=nu&age=18", headers:{'Content-Type':'application/x-www-form-urlencoded'} }) .then(res=>res.text()) //使用text还是jsonp取决于传过来的数据 .then(res=>{ console.log(res) }) } </script> </html>
    Processed: 0.009, SQL: 9