GET 请求(send 不带参数)
GET 请求的参数必须拼接在 URL 中,send() 里不传任何数据。
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/users?id=123&name=John');
xhr.send(); // 无请求体
POST 请求(通过 send 传递参数)
根据后端接口要求,send() 可以传入不同格式的数据:
① 发送 URL 编码格式(表单提交)
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/login');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
const data = 'username=admin&password=123456';
xhr.send(data);
② 发送 JSON 格式(REST API 常用)
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/user');
xhr.setRequestHeader('Content-Type', 'application/json');
const data = JSON.stringify({ name: 'Alice', age: 25 });
xhr.send(data);
③ 发送 FormData 对象(含文件上传)
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('username', 'Tom');
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/upload');
// 不要手动设置 Content-Type,浏览器会自动加上 multipart/form-data 边界
xhr.send(formData);
④ 发送 Blob / ArrayBuffer(二进制数据)
const blob = new Blob(['Hello World'], { type: 'text/plain' });
xhr.send(blob);
1. data 参数的基本格式
data 可以是 对象 、字符串 或 FormData:
$.ajax({
url: 'https://api.example.com/endpoint',
method: 'POST', // 或 'GET'
data: { ... }, // 核心传参
success: function(res) { ... }
});
2. 不同请求方法下的数据传递
GET 请求 ------ 自动拼接到 URL
当 method: 'GET' 时,data 对象会被 jQuery 自动转换为查询字符串追加到 URL 后面,不会产生请求体。
$.ajax({
url: 'https://api.example.com/users',
method: 'GET',
data: { id: 123, name: 'John' }
});
// 实际请求 URL: /users?id=123&name=John
POST / PUT / PATCH / DELETE ------ 发送请求体
默认情况下,jQuery 会将 data 对象序列化为 application/x-www-form-urlencoded 格式的字符串放在请求体中。
$.ajax({
url: 'https://api.example.com/user',
method: 'POST',
data: { name: 'Alice', age: 25 }
});
// 请求体: name=Alice&age=25
// Content-Type: application/x-www-form-urlencoded; charset=UTF-8
3. 自定义 contentType 发送不同数据格式
① 发送 JSON(REST API 常用)
需要设置 contentType: 'application/json',并将 data 手动转为 JSON 字符串
$.ajax({
url: 'https://api.example.com/user',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: 'Alice', age: 25 }),
// 或者使用 data: { ... } 配合 processData: false? 不推荐,下面会讲
});