什么是ajax
Ajax不是某种编程语言
是一种在无需重新加载整个网页的情况下,能够局部更新网页的技术
同步和异步
同步:客户端向服务器端发送请求的时候,用户不能进行其他的操作
烧水完毕之后 才可以看书
异步:客户端向服务器端发送请求的时候,用户可以进行其他的操作
烧水的同时 可以看书
定时器模仿异步
<script>console.log(1);setTimeout(()=>{console.log("http")},1000)console.log(2);</script>先输出1,再输出2,最后输出http
封装ajax
<script>function ajax({url,method,success}){/* ajax 如何使用ajax向后台获取数据*//* 1. 创建ajax核心对象*/var xhr = new XMLHttpRequest();/* 2.与服务器建立连接 xhr.open(method,url,async)请求的方式,地址,是否异步*/xhr.open("get",url,true)/* 3.发送请求 */xhr.send()/* 4.响应 *//* onreadystatechange 监听服务器的响应状态*/xhr.onreadystatechange = function(){/* xhr.status 服务器端响应的状态码 200 *//* xhr.readyState 服务器响应的进度 4 响应已经完成 */if(xhr.readyState == 4 && xhr.status == 200){var res = JSON.parse(xhr.responseText);/* JSON.parse() 可以json格式的字符串,转换为json格式的数据 */success(res);}}}ajax({url:"http://192.168.4.18:8000/",method:"get",success:res=>console.log(res)})</script>
