ajax笔记
视频资料:
云盘视频:https://www.aliyundrive.com/s/MHZxZtkbqbc
ajax:
ajax定义:
ajax(异步的JavaScript和xml)
- ajax的使用:
- 创建 XMLHttpRequest 对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
- 创建 XMLHttpRequest 对象
- 发送请求
xhttp.open("GET/POST", "servlet", true);
xhttp.send();
- ajax的常用属性:
onreadystatechange
onreadystatechange属性可以在网页加载完成后自动调用ajax请求,具体代码如下:xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
axios:
- axios官网:
www.axios-http.cn - axios的使用:
- html内引入axios
- 使用 jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- 使用 jsDelivr CDN:
- html内引入axios
- 使用 unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- 使用axios发送请求,并获得响应结果:
axios({
method:"get/post"
url:""
}).then(function(resp){
alert(resp.data)
})
- axios的带参发送请求:
- 网页(前端):
//get方式参数只能卸载url里
axios({
method:"get"
url:"/xxx?xxx=xxx&xxx=xxx"
}).then(function(resp){
alert(resp.data)
})
//post方式可以写在单独的data里
axios({
method:"get"
url:"/xxx"
data:"xxx=xxx&xxx=xxx"
}).then(function(resp){
alert(resp.data)
})
- 网页(前端):
- servlet(后端):
//接收前端传的参
String xxx = request.getParameter("xxx");
//做业务
xxxxxxxxxxxxxxxxxx;
//给前端返回参数
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("xxx");
- axios请求方法的别名使用:
- get请求:
axios.get("url").then(function(resp){
alert(resp.data);
})
- get请求:
- post请求:
axios.post("url","参数").then(function(resp){
alert(resp.data);
})
![QQ截图20220502201458.png](https://cdn.nlark.com/yuque/0/2022/png/28453019/1651493956868-68ebebd2-0eb2-45ae-b96a-7e3409162eb5.png#clientId=ucf20a060-063f-4&crop=0&crop=0&crop=1&crop=1&from=drop&id=ud06b6e50&margin=%5Bobject%20Object%5D&name=QQ%E6%88%AA%E5%9B%BE20220502201458.png&originHeight=431&originWidth=328&originalType=binary&ratio=1&rotation=0&showTitle=false&size=67097&status=done&style=none&taskId=u3debf91d-c76e-446d-8222-3e6482fe5f5&title=)