欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > 前端(三):Ajax

前端(三):Ajax

2024/10/25 0:24:49 来源:https://blog.csdn.net/qq_52200849/article/details/140908896  浏览:    关键词:前端(三):Ajax

一、Ajax

Asynchronous JavaScript And XML,简称Ajax,是异步的JavaScript和XML。
作用:数据交换,通过Ajax可以给服务器发送请求,并获取服务器响应的数据。异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用的校验等。

(一)原生Ajax请求

1、创建XMLHttpRequest对象:用于和服务器交换数据
2、向服务器发送请求
3、获取服务器响应数据
在这里插入图片描述

(二)Axios

对原生Ajax的封装,简化书写,快速开发。
官网:https://www.axios-http.cn/
在这里插入图片描述
实例:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../JS/axios.min.js"></script><script src="../JS/vue.js"></script>
</head>
<body><input type="button" value="获取数据get" onclick="get()"><input type="button" value="删除数据post" onclick="post()">
</body>
<script>function get(){axios({/* 通过get发送异步请求 */method:"get",url:"https://yapi.pro/mock/478286/userGetByID"}).then((result) => {console.log(result);})function post(){axios({/* 通过post发送异步请求 */method:"post",url:"http://yapi.smart-xwork.cn/mock/478286/deleteById",data:"id = 1"}).then((result) => {console.log(result);})}
</script>
</html>

请求方式别名:
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../JS/axios.min.js"></script><script src="../JS/vue.js"></script>
</head>
<body><input type="button" value="获取数据get" onclick="get()"><input type="button" value="删除数据post" onclick="post()">
</body>
<script>function get(){// axios({//     /* 通过get发送异步请求 *///     method:"get",//     url:"https://yapi.pro/mock/478286/userGetByID"// }).then((result) => {//     console.log(result.data);// })axios.get("https://yapi.pro/mock/478286/userGetByID").then(result =>{console.log(result);})}function post(){//axios({//    /* 通过post发送异步请求 *///    method:"post",//     url:"http://yapi.smart-xwork.cn/mock/169327/emp/deleteById",//     data:"id = 1"// }).then((result) => {//     console.log(result.data);// })axios.post("https://yapi.pro/mock/478286/deleteByID","id=1").then(result =>{console.log(result);})}
</script>
</html>

结果(在Yapi中设置了端口才可以连接!,详情请看:):
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com