博客目录
- 一.AJAX 的格式
- 1.JSON 格式
- 2.表单格式
- 3.文件格式
- 4.查询参数格式
- 二.如何接受数据
- 1.xhr.responseText
- 2.实战
一.AJAX 的格式
AJAX (Asynchronous JavaScript and XML) 请求通常使用以下几种常见的格式:
1.JSON 格式
- 请求头:
Content-Type: application/json
- 请求体: 一个 JSON 格式的字符串
示例:
const data = { name: "John", age: 30 };
fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
2.表单格式
表单格式 (application/x-www-form-urlencoded):
- 请求头:
Content-Type: application/x-www-form-urlencoded
- 请求体: 一个 URL 编码的查询字符串
示例:
const formData = new URLSearchParams();
formData.append("name", "John");
formData.append("age", "30");
fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: formData,
});
3.文件格式
Multipart/form-data 格式:
- 请求头:
Content-Type: multipart/form-data
- 请求体: 包含文本字段和文件字段的多部分消息体
示例:
const formData = new FormData();
formData.append("name", "John");
formData.append("avatar", file);
fetch("/api/users", {
method: "POST",
body: formData,
});
4.查询参数格式
查询参数格式:
- 请求头:
Content-Type: application/x-www-form-urlencoded
- 请求 URL: 包含查询参数的 URL
示例:
fetch("/api/users?name=John&age=30", {
method: "GET",
});
二.如何接受数据
1.xhr.responseText
var response = JSON.parse(xhr.responseText);
console.log(response.message);
2.实战
$.ajax({
type: "post",
url: "/user/register",
data: {
username: userName,
password1: passWord1,
password2: passWord2,
number: number,
},
async: true,
success: function (res) {
layer.msg("注册成功!", { icon: 6 });
window.location.href = "/";
},
error: function (xhr, type) {
var response = JSON.parse(xhr.responseText);
console.log(response.message);
if (xhr.status == 401 || xhr.status == 403) {
layer.msg("注册失败:" + response.message, { icon: 5 });
}
},
});
觉得有用的话点个赞 👍🏻
呗。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄
💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍
🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙