# 發送 POST 請求(模擬用戶登錄操作)
需求:模擬用戶登錄操作。
* 編寫頁面:
~~~
<span id="result"></span>
<form id="loginForm">
? ?<input type="text" id="username" name="username" placeholder="用戶名">
? ?<input type="text" id="password" name="username" placeholder="密碼">
? ?<input id="login" type="button" value="登錄">
</form>
~~~
* 編寫 AJAX 代碼:
* ## 注意加上
~~~
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
~~~
~~~
window.onload = function(){
? ?var loginEle = document.querySelector('#login');
? ?loginEle.onclick = function(){
? ? ? ?var username = document.getElementById('username').value;
? ? ? ?var password = document.getElementById('password').value;
? ? ? ?var params = 'username=' + username + '&password=' + password;
?
? ? ? ?var ajax = new XMLHttpRequest();
?
? ? ? ?ajax.open('post', '/login', true);
? ? ? ?// 參數進行 URL 編碼,不然后臺代碼無法獲取請求體中的參數
? ? ? ?ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
?
? ? ? ?ajax.onreadystatechange = function () {
? ? ? ? ? ?if(ajax.readyState == 4 && ajax.status == 200){ // 代表后臺處理完畢且響應 200
? ? ? ? ? ? ? ?// 執行對應邏輯
? ? ? ? ? ? ? ?console.log(ajax.responseText);
? ? ? ? ? ? ? ?document.getElementById('result').innerText = ajax.responseText;
? ? ? ? ? }
? ? ? }
? ? ? ?ajax.send(params);
? }
}
~~~
* 編寫后臺代碼:
* ## 注意加上中間件app.use(express.urlencoded());
~~~
const express = require('express');
const app = express();
?
app.use(express.urlencoded());
app.use('/static', express.static(path.join(__dirname, 'static')));
?
app.post('/login', (req, res) => {
? ?console.log(req.body);
? ?if('zs' == req.body.username && '12345' == req.body.password){
? ? ? ?res.send('登錄成功');
? }else{
? ? ? ?res.send('登錄失敗');
? }
});
?
app.listen(8888, () => {
? ?console.log('running...');
});
~~~
# 超時處理
有時網絡會出現問題或者服務端出問題導致請求時間過長,一般提示網絡請求稍后重試,以增加用戶的體驗感。在代碼中我們可以通過定時器和請求中斷來實現超時處理的效果。
~~~
var timer = setTimeout(function () {
? ?// 中斷請求
? ?ajax.abort();
}, 5000);
~~~
# 方法抽取
```
function ajax(mehtod, url, param, success, time){
var ajax;
try { // 非 IE
ajax = new XMLHttpRequest();
}
catch (e) { // IE
ajax = new ActiveXObject('Microsoft.XMLHTTP');
}
if(method == 'get'){
param = encodeURI(param);
url = url + '?' + param;
param = null;
}
ajax.open(method, url, true);
if(method == 'post'){
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
ajax.onreadystatechange = function () { // onload
if(ajax.readyState == 4 && ajax.status == 200){
success(ajax.responseText);
}
}
ajax.send(param);
var timer = setTimeout(function () {
ajax.abort();
}, time);
}
```