详细解析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/