詳細解析Ajax的使用之向服務器發送GET請求
上篇文章講的如何使用Ajax發送get請求,這篇文章說如何使用Ajax發送post請求。
HTML代碼:
<h1>ajax的post請求</h1>
<button id="btn">發送請求</button>
JavaScript代碼:
var oBtn = document.getElementById("btn");
// 1.初始化請求對象
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
console.log(xhr.readyState);
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.發送請求
// 2-1.設置請求的方式 地址等
xhr.open("POST", "post.php", true);
console.log(xhr.readyState);
// 2-2.設置請求頭
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 2-3.發送請求
xhr.send("user=zhangsan&psw=654321");
console.log(xhr.readyState);
xhr.onreadystatechange = function () {
oBtn.onclick = function () {
console.log(xhr.readyState);
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
PHP代碼:
<?php
$user=$_POST["user"];
$psw=$_POST["psw"];
echo "用戶名:{$user},密碼:{$psw}";
?>
總結: post請求主要是向服務器發送數據,發送的數據也不會拼接在URL後面,安全性較高,而且允許的數據大小比較大。
視頻講解鏈接:
https://www.bilibili.com/video/BV1Lt4y1y7Ae/