XMLHttpRequest 或 fetch 物件。Content-Type: application/json。JSON.stringify(data)。
function postJSON(url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback(new Error("HTTP " + xhr.status), null);
}
}
};
xhr.send(JSON.stringify(data));
}
// 使用
postJSON("/api/users", {name: "Alice", age: 25}, function(err, res) {
if (err) console.error(err);
else console.log("Success:", res);
});
async function postJSONFetch(url, data) {
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 res.json();
}
postJSONFetch("/api/users", {name: "Bob", age: 30})
.then(console.log)
.catch(console.error);
JSON.stringify:IE8+ 原生支援,IE7 需引入 json2.js。fetch:IE 不支援,需 whatwg-fetch polyfill。Access-Control-Allow-Origin 標頭。「自己用 js 轉為鍵值對字符串... 用 JSON.parse 轉為字符串後傳遞...」