javascript通过ajax提交json数据需设置content-type为application/json并用json.stringify()序列化对象;推荐fetch api,兼容环境可用xmlhttprequest;注意避免漏设头、未序列化、服务端解析配置及跨域问题。

JavaScript 通过 Ajax 提交 JSON 格式的 POST 数据,核心是设置正确的请求头(Content-Type: application/json)并把 JavaScript 对象序列化为 JSON 字符串后作为请求体发送。
使用 fetch API(推荐)
现代浏览器中首选 fetch,简洁且基于 Promise:
- 用
JSON.stringify()将对象转成 JSON 字符串 - 设置
headers中的Content-Type为application/json -
method设为'POST',body填入序列化后的字符串
示例:
const data = { username: 'alice', age: 30 };
fetch('/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => console.log(result))
.catch(err => console.error('提交失败:', err));
使用 XMLHttpRequest(兼容旧环境)
需要手动配置请求头和监听响应状态:
- 调用
xhr.setRequestHeader()设置Content-Type - 用
JSON.stringify()处理数据 -
xhr.send()直接传入字符串(不要传对象) - 检查
xhr.status === 200和xhr.readyState === 4再解析响应
示例:
const xhr = new XMLHttpRequest();
const data = { username: 'bob', email: 'bob@example.com' };
xhr.open('POST', '/api/register');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status console.error('网络错误');
xhr.send(JSON.stringify(data));
常见错误与注意事项
提交失败常因以下细节疏忽:
-
漏掉
Content-Type头:服务端可能拒绝或按表单方式解析,导致字段丢失 -
body 传了对象没 stringify:会变成
[object Object],后端收不到有效 JSON -
服务端未正确解析 JSON:如 Express 需
app.use(express.json());PHP 需用file_get_contents('php://input')再json_decode() -
跨域问题:若接口在不同域名,确保服务端设置了
Access-Control-Allow-Origin等 CORS 头
配合 async/await 写法(fetch 进阶)
让异步逻辑更清晰可读:
async function postJson(url, data) {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('请求异常:', err);
throw err;
}
}
// 调用
postJson('/api/login', { token: 'abc123' })
.then(data => console.log('登录成功:', data));
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











