一、ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ajax</title>
</head>
<body></body>
</html>
<!-- 先引入再使用 -->
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
$(function () {
$.ajax({
// 请求方式
type: "",
// 接口地址
url: "",
// 数据的格式
dataType: "json",
// 传递的参数
data: {
key: value,
},
// 请求头
headers: {
"content-type": "application/x-www-form-urlencoded",
},
// 同步
async: true,
// 成功的回调
success: function (res) {},
// 失败的回调
error: function (res) {},
});
});
</script>
二、get
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get</title>
</head>
<body></body>
</html>
<!-- 先引入再使用 -->
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
$(function () {
$.ajax({
// 请求方式
type: "get",
// 请求地址
url: "https://geoapi.qweather.com/v2/city/lookup",
// 请求的参数
data: {
location: "北京",
key: "2fcca52baf1b483e8e56330259afb9a1",
},
// 数据的格式
dataType: "json",
// 同步异步
async: true,
// 成功的回调
success: function (res) {
console.log(res);
},
});
});
</script>
三、post
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>post</title>
</head>
<body>
<input type="text" />
<button>翻译</button>
</body>
</html>
<!-- 先引入再使用 -->
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
$(function () {
$("button").click(function () {
$.ajax({
type: "post",
url: "https://api.oioweb.cn/api/txt/QQFanyi",
data: {
sourceText: $("input").val(),
},
dataType: "json",
// 请求头
headers: {
"content-type": "application/x-www-form-urlencoded",
},
// 同步异步
async: true,
success: function (res) {
console.log(res);
},
});
});
});
</script>