说明:ajax是一门异步处理请求的技术;可以实现不重新加载整个页面的情况下,访问后台后服务;比如百度搜索引擎,输入关键字后,下面会实时出现待选项,这就是一种异步处理请求的技术。
原生Ajax
原生的Ajax是通过js中的XMLHttpRequest来实现的,流程繁琐,不推荐使用。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>原生Ajax</title>
</head>
<body><!-- 鼠标移动到按钮上,向后端发送请求 --><input type="button" value="获取数据" onmouseover="getData()"><div id="div1"></div></body>
<script>function getData(){//1. 创建XMLHttpRequest var xmlHttpRequest = new XMLHttpRequest();//2. 发送异步请求xmlHttpRequest.open('GET','http://yapi.smart-xwork.cn/mock/169327/emp/list');xmlHttpRequest.send();//发送请求//3. 获取服务响应数据xmlHttpRequest.onreadystatechange = function(){if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){// 4. 将获取到的数据显示在div1盒子中document.getElementById('div1').innerHTML = xmlHttpRequest.responseText;}}}
</script>
</html>
Axios
Axios对ajax进行了封装,简化了书写,使用前需要引用;
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Ajax-Axios</title><!-- 使用前需要先引用 --><script src="js/axios-0.18.0.js"></script></head><body><!-- 鼠标移动到按钮上,向后端发送请求 --><input type="button" value="获取数据" onmouseover="get()"></body>
<script>function get() {// 发请求给服务器axios.get("http://yapi.smart-xwork.cn/mock/169327/emp/list").then(resp => {// 将接收到的结果显示在控制台中console.log(resp.data);})}</script></html>