<!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>Document</title>
</head>
<body>
<button id="btn1">get</button>
<button id="btn2">post</button>
<button id="btn3">axios通用函数发送,用的比较多</button>
<button id="btn4">fetch通用函数发送,用的比较少</button>
</body>
</html>
<script crossorigin="anonymous" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script>
// url简写,后面只用写/就代表http://127.0.0.1:8000
axios.defaults.baseURL = "http://127.0.0.1:8000"
$("#btn1").click(
function () {
axios.get(
//第一个参数是url地址
"/axios",
// 第二个参数是请求头,url参数等
{
// (就是地址栏后面加的,只能用于get请求)
params: {
id: 10,
vip: 7
},
// 请求头信息
headers: {
name: 'atguigu'
}
// 在get或者post方法的后面.then,获得响应
}
).then(
value => {
console.log(value);
})
}
);
$('#btn2').click(
function () {
axios.post(
// 第一个参数是请求地址
"http://127.0.0.1:8000/axios",
// 第二个是请求体
{
name: 10, pwd: 200
},
// 第三个是其他的参数,比如请求头
{
// 设置请求头
headers: {
name: 'atguigu'
},
//即使是post请求,也可以设置url参数
params: {
id: 10,
vip: 7
},
}
// 在get或者post方法的后面.then,获得响应
).then(
value => {
console.log(value);
})
}
);
$('#btn3').click(
function () {
axios({
method: 'POST',
url: "/axios",
// url后的参数
params: {
vip: 10,
level: 30
},
// 请求头参数
headers: {
a: 100,
b: 200
},
data: {
uname: 'admin',
password: '123'
}
}).then(
value => {
console.log(value);
})
});
$('#btn4').click(
function () {
fetch("http://127.0.0.1:8000/axios?url_vip:10&url_level:30,",
{
method:'post',
// 请求头参数
headers: {
request_headers_a: 100,
request_headers_b: 200
},
// 设置请求体
body:
"request_body_uname= 'admin'&&request_body_password: '123'"
}
).then(response=>
{ //获得响应体
return response.text();
// 如果响应体是json应该用
return response.json();
}).then(response=>{
console.log(response);
})
}
)
</script>
axios方式发送ajax,语法类似,但更简单
最新推荐文章于 2024-10-06 15:51:50 发布