首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

原生 JavaScript AJAX 發送 JSON 資料完整指南(無 jQuery 依賴)

     編輯:程式設計綜合問答

核心步驟

  1. 建立 XMLHttpRequest 或 fetch 物件。
  2. 設定 Content-Type: application/json。
  3. 將 JS 物件序列化為 JSON 字串:JSON.stringify(data)。
  4. 送出請求並處理回應。

XMLHttpRequest 完整範例


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);
});

Fetch API 現代寫法(推薦)


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 轉為字符串後傳遞...」

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved