1.1 AJAX简介
AJAX全称为 Asynchronously JavaScript And XML,就是异步的JS和XML,通过AJAX可以在浏览器中向服务器发送异步请求,最大优势是无刷新获取数据
1.2 XML简介
XML被设计用来传输和存储数据,XML和HTML类似,不同的是HTML中都是预定义的比爱钱,而XML没有预定义标签,全都是自定义标签,用来表示一些数据
现在传输数据格式已经变味了JSON,取代了XML
AJAX的特点
优点
- 可以无需刷新页面和服务器端进行通信
- 允许你根据用户实际来更新部分页面内容
缺点
#AJAX请求基本操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| //GET const result=document.getElementById("text") btn.onclick=function(){ //创建对象 const xhr=new XMLHttpRequest(); //初始化 设置请求方法和URL xhr.open('GET','http://127.1.0.1/server'); //发送 xhr.send(); //事件绑定 处理服务端返回结果 //readystate是xhr对象中的属性,表示状态 0 1 2 3 4 ,4表示拿到了所有数据 xhr.onreadystatechange=function(){ if(xhr.readystate===4){ if(xhr.status>=200&&xhr.status<300){ result.innerHTML=xhr.response //接受响应体 } } } }
//POST const result =document.getElementById("result"); result.addEventListener("mouseover",function(){ //创建对象 const xhr=new XMLHttpRequest() //初始化 设置类型与URL xhr.open('POST','http://127.0.1:8000/server') //发送 xhr.send() //事件绑定 xhr.onreadystatechange=function(){ if(xhr.readystate===4){ if(xhr.status>=200&&xhr.status<300){ //处理服务端返回结果 result.innerHTML=xhr.response
} } } })
|