發送POST請求
POST 請求過程中,都是采用請求體承載需要提交的數據
var xhr = new XMLHttpRequest()
// open 方法的第一個參數的作用就是設置請求的 method xhr.open('POST', './add.php')
// 設置請求頭中的 Content‐Type 為 application/x‐www‐form‐urlencoded // 標識此次請求的請求體格式為 urlencoded 以便於服務端接收數據 xhr.setRequestHeader('Content‐Type', 'application/x‐www‐form‐urlencoded')
// 需要提交到服務端的數據可以通過 send 方法的參數傳遞 // 格式:key1=value1&key2=value2 xhr.send('key1=value1&key2=value2')
xhr.onreadystatechange = function () { if (this.readyState === 4) { console.log(this.responseText) } }
練習代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AJAX發送POST請求</title> <style> #loading { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #555; opacity: .5; text-align: center; line-height: 300px; } #loading::after { content: '加載中...'; color : #fff; } </style> </head> <body> <div id="loading"></div> <table border="1"> <tr> <td>用戶名</td> <td><input type="text" id="username"></td> </tr> <tr> <td>密碼</td> <td><input type="password" id="password"></td> </tr> <tr> <td></td> <td><button id="btn">登錄</button></td> </tr> </table> <script> // 找一個合適的時機,做一件合適的事情 var btn = document.getElementById('btn') // 1. 獲取界面上的元素 value var txtUsername = document.getElementById('username') var txtPassword = document.getElementById('password') var loading = document.getElementById('loading') btn.onclick = function () { loading.style.display = 'block' var username = txtUsername.value var password = txtPassword.value // 2. 通過 XHR 發送一個 POST 請求 var xhr = new XMLHttpRequest() xhr.open('POST', 'login.php') // !!! 一定注意 如果請求體是 urlencoded 格式 必須設置這個請求頭 !!! xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') // xhr.send('username=' + username + '&password=' + password) xhr.send(`username=${username}&password=${password}`) // 3. 根據服務端的反饋 作出界面提示 xhr.onreadystatechange = function () { if (this.readyState !== 4) return console.log(this.responseText) loading.style.display = 'none' } } </script> </body> </html>