在 javascript 中發送 post 請求的步驟:創建 xmlhttprequest 對象。配置請求的 url、方法、請求頭等信息。準備發送數據,并使用 json.stringify() 轉換為 json 字符串。將數據作為參數傳遞給 send() 方法。使用 onreadystatechange 事件監聽器處理響應。當 xhr.readystate === 4 且 xhr.status === 200 時,請求已成功,可以使用 xhr.responsetext 獲取響應數據。
如何使用 JavaScript 發送 POST 請求
在 JavaScript 中發送 POST 請求的過程如下:
創建 XMLHttpRequest 對象
const xhr = new XMLHttpRequest();
配置請求
xhr.open(‘POST’, url, true);
xhr.setRequestHeader(‘Content-Type’, ‘application/json’);
xhr.setRequestHeader(‘X-Requested-With’, ‘XMLHttpRequest’);
為準備發送做準備
將要發送的數據作為參數傳遞給 send() 方法。
xhr.send(JSON.stringify(data));
處理響應
xhr.onreadystatechange = function() { … };
當 xhr.readyState === 4 并且 xhr.status === 200 時,請求已成功。
使用 xhr.responseText 獲取響應數據。
示例:
const data = { name: 'John Doe', age: 30 };
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
登錄后復制






