AJAX GET 请求
AJAX PUT 请求 

AJAX POST 请求

POST 请求用于将数据从网页发送到 Web 服务器。在此请求中,数据在与 URL 分离的请求正文中发送。我们可以将此请求与open() 方法一起使用。


语法:

open('POST', url, true)

其中,open() 方法需要三个参数 

  • POST - 它用于将数据发送到Web服务器。

  • url - url表示服务器(文件)位置。

  • true − 对于异步连接,将值设置为 true。或者,对于同步连接,将值设置为 false。此参数的默认值为 true。


如何使用 POST 请求

步骤1 - 创建XMLHttpRequest的对象。

var xhrRequest = new XMLHttpRequest();

第 2 步 - 在创建 XMLHttpRequest 对象后,现在我们必须定义一个回调函数,该函数将在从 Web 服务器获取响应后触发。

xhrRequest .onreadystatechange = function(){
   // 回调处理逻辑
}

步骤3 - 现在我们使用 open() 函数。在 open() 函数内部,我们传递一个 POST 请求以及我们必须向其发送数据的 URL。

xhrRequest.open("POST", url, async);

步骤4 - 使用 setRequestHeader() 设置 HTTP 头请求。它总是在 open() 方法之后但在 send() 方法之前调用。这里,content-type 标头设置为“application/json”,表示数据将以 JSON 格式发送。

xhrRequest.setRequestHeader('Content-type', 'application/json')

第 5 步 - 最后,我们使用 stringify() 方法将 JSON 数据转换为字符串,然后使用 send() 方法将其发送到 Web 服务器。

xhrRequest.send(JSON.stringify(JSONdata))


使用示例:

<!DOCTYPE html>
<html>
<head>
<script>
function sendPost() {
// 创建 XMLHttpRequest 对像
var xhrRequest = new XMLHttpRequest();
      
// 定义回调函数
xhrRequest.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 201) {
            document.getElementById("sample").innerHTML = this.responseText;
            console.log("Data Send Successfully")
         }
};
      
// 打开连接
xhrRequest.open("POST", "/tutorial/try.php?act=getProv", true);
     
// 设置请求头
xhrRequest.setRequestHeader('Content-type', 'application/json')
      
// 向服务器发送请求
xhrRequest.send(JSON.stringify({
    "id": 21
}));
}
</script>
</head>
<body>
<h2>发送 POST 请求示例</h2>
<button type="button" onclick="sendPost()">发送</button>
<div id="sample"></div>
</body>
</html>

亲自试试


这就是 XMLHttpRequest 发送 POST 请求的方式。这是向服务器发送或发布数据的最常用方法。