js中send的作用和使用 $.ajax的作用

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? 不推荐,下面会讲
});
相关推荐
Rabbit_QL1 小时前
npm 不是“前端的包管理器“—它是 Node.js 的
前端·npm·node.js
鸿儒5171 小时前
记录一个C++ Windows程序移植到Linux系统的bug
开发语言·c++·bug
浮尘笔记1 小时前
在Snowy后台无需编码实现自动化生成CRUD操作流程
java·开发语言·经验分享·spring boot·后端·程序人生·mybatis
jinanwuhuaguo1 小时前
OpenClaw执行奇点——因果链折叠与责任悬置的时间哲学(第十九篇)
前端·人工智能·安全·重构·openclaw
为美好的生活献上中指1 小时前
本地虚拟机部署redis集群
前端·redis·ubuntu·bootstrap·html·redis集群
MoonBit月兔1 小时前
MoonBit 作为重大成果亮相广东省人工智能应用对接大会,展示 AI 原生编程语言最新进展
开发语言·人工智能·moonbit
c++之路2 小时前
C++ 预处理器
开发语言·c++
ConardLi2 小时前
开源我的 GPT-Image2 生图 Skill,附大量玩法指南
前端·人工智能·后端
我是Superman丶2 小时前
Antigravity Retry 自动重试脚本
前端·javascript·vue.js