GET 把参数放在 URL 查询字符串里,适合读取数据;POST 把数据放在请求体中,适合提交和修改数据。两种方式都可以用 fetch 完成。
本节要点
- 查询参数要用 encodeURIComponent 编码,避免特殊字符破坏 URL。
- 发送 JSON 时需要设置 Content-Type: application/json。
- 请求体使用 JSON.stringify 把对象转成字符串。
- GET 请求不应产生副作用,POST 更适合新增或修改。
可运行示例
页面会先用 GET 发送关键词,再用 POST 提交一份 JSON,并对比服务端收到的内容。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>GET 与 POST</title>
</head>
<body>
<h1>GET 与 POST</h1>
<form id="form">
<label>关键词:<input id="keyword" value="fetch 教程"></label>
<button type="submit">发送</button>
</form>
<pre id="output"></pre>
<script>
document.getElementById('form').addEventListener('submit', async (event) => {
event.preventDefault();
const keyword = document.getElementById('keyword').value;
const output = document.getElementById('output');
const getUrl = '/ajax/demo/echo.php?q=' + encodeURIComponent(keyword);
const getResponse = await fetch(getUrl);
const getData = await getResponse.json();
const postResponse = await fetch('/ajax/demo/echo.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ q: keyword, page: 1 })
});
const postData = await postResponse.json();
output.textContent = JSON.stringify({ get: getData, post: postData }, null, 2);
});
</script>
</body>
</html>运行说明:提交表单后,对比 get.query.q 与 post.json.q,理解参数分别放在哪里。 在线运行示例 →
参数位置对比
| 方式 | 参数位置 | 读取方式 |
|---|---|---|
| GET | URL 的 ? 后面 | 服务端读取查询字符串 |
| POST(表单) | 请求体 multipart 或 urlencoded | 服务端读取表单字段 |
| POST(JSON) | 请求体,格式为 JSON | 读取原始输入并解析 JSON |
编码的重要性
空格、中文、&、= 等字符在 URL 中有特殊含义。使用 encodeURIComponent 可以把它们安全地编码,服务端解码后才能拿到原始值。
提示:发送 FormData 时不要手动设置 Content-Type,浏览器会自动生成带 boundary 的 multipart 头。