发送 POST 其实很简单可以在之前发送 GET 请求的基础上进行更改一些内容即可进行发送 POST 请求了:
官方文档地址:https://www.w3school.com.cn/js/js_ajax_http_send.asp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax-post</title>
<script>
window.onload = function () {
let oBtn = document.querySelector("button");
oBtn.onclick = function () {
let xhr;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "ajax-post.php", true);
// 注意点: 以下代码必须放到open和send之间
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("userName=zs&userPwd=321");
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304) {
// alert("请求成功");
alert(xhr.responseText);
} else {
alert("请求失败");
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
ajax-post.php:
<?php
$arr = array(1, 3, 5);
print_r($arr);
?>
本文不涉及然和的介绍和其它的相关内容,只是博主简单的记录一下封装 POST 的代码:
myAjax.js:
const obj2str = (obj) => {
// 如果没有传参, 为了添加随机因子,必须自己创建一个对象
obj = obj || {};
obj.t = new Date().getTime();
let res = [];
for (let key in obj) {
// 在URL中是不可以出现中文的, 如果出现了中文需要转码
// 可以调用encodeURIComponent方法
// URL中只可以出现字母/数字/下划线/ASCII码
res.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
return res.join("&");
}
const ajax = (type, url, obj, timeout, success, error) => {
// 0.将对象转换为字符串
// key=value&key=value;
let str = obj2str(obj);
// 1.创建一个异步对象
let xmlHttp, timer;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求方式和请求地址
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
if (type === "GET") {
xmlHttp.open(type, url + "?" + str, true);
// 3.发送请求
xmlHttp.send();
} else {
xmlHttp.open(type, url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(str);
}
// 4.监听状态的变化
xmlHttp.onreadystatechange = (event) => {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if (xmlHttp.readyState === 4) {
clearInterval(timer);
// 判断是否请求成功
if (xmlHttp.status >= 200 && xmlHttp.status < 300 ||
xmlHttp.status === 304) {
// 5.处理返回的结果
// console.log("接收到服务器返回的数据");
success(xmlHttp);
} else {
// console.log("没有接收到服务器返回的数据");
error(xmlHttp);
}
}
}
// 判断外界是否传入了超时时间
if (timeout) {
timer = setInterval(() => {
console.log("中断请求");
xmlHttp.abort();
clearInterval(timer);
}, timeout);
}
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax-post</title>
<script src="myAjax.js"></script>
<script>
window.onload = function () {
let oBtn = document.querySelector("button");
oBtn.onclick = function () {
ajax("POST", "ajax-post.php", {
"userName": "BNTang",
"userPwd": "123"
}, 3000, (xhr) => {
alert(xhr.responseText)
}, () => {
console.log("请求失败");
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
ajax-post.php:
<?php
echo $_POST["userName"];
echo $_POST["userPwd"];
?>
在经过博主前几篇的文章过来之后,本文首先将介绍一下使用 jQuery 当中的 Ajax,说明,在看本文的 jquery 当中的 Ajax 需要导入 jQuery,官方文档地址:https://jquery.cuishifeng.cn/index.html
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="../js/jquery-1.12.4.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
$.ajax({
url: "ajax-jquery.php",
type: "get",
data: "userName=BNTang&userPwd=654321",
success: (msg) => {
alert(msg);
},
error: (xhr) => {
alert(xhr.status);
}
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
如上代码的特点,就是属性当中的位置可以任意改变,type 属性当中的 get 与 post 可以大小写都可以进行请求,看了如上 jQuery 当中的 ajax 方法之后然后我们再来看看我们自己封装的 ajax 试着与 jQuery 当中的 ajax 的特点去试着发送请求看一下,导入我们自己的 ajax 方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="myAjax.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
ajax("get", "ajax-jquery.php", {
"userName": "BNTang",
"userPwd": "123456"
}, 3000, (msg) => {
alert(msg.responseText);
}, (xhr) => {
alert(xhr.status);
}
);
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
很显然是不可以的,那么我们这个时候就需要在完善一下我们自己封装 ajax 代码了,完善的要与 jQuery 当中的特点一致的话其实就只需要抽取一个对象来进行接收参数即可:
const obj2str = (data) => {
data = data || {};
data.t = new Date().getTime();
let res = [];
for (let key in data) {
// 在URL中是不可以出现中文的, 如果出现了中文需要转码
// 可以调用encodeURIComponent方法
// URL中只可以出现字母/数字/下划线/ASCII码
res.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return res.join("&");
}
const ajax = (option) => {
// 0.将对象转换为字符串
// key=value&key=value;
let str = obj2str(option.data);
// 1.创建一个异步对象
let xmlHttp, timer;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求方式和请求地址
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
if (option.type.toLowerCase() === "get") {
xmlHttp.open(option.type, option.url + "?" + str, true);
// 3.发送请求
xmlHttp.send();
} else {
xmlHttp.open(option.type, option.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(str);
}
// 4.监听状态的变化
xmlHttp.onreadystatechange = (event) => {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if (xmlHttp.readyState === 4) {
clearInterval(timer);
// 判断是否请求成功
if (xmlHttp.status >= 200 && xmlHttp.status < 300 ||
xmlHttp.status === 304) {
// 5.处理返回的结果
// console.log("接收到服务器返回的数据");
option.success(xmlHttp);
} else {
// console.log("没有接收到服务器返回的数据");
option.error(xmlHttp);
}
}
}
// 判断外界是否传入了超时时间
if (option.timeout) {
timer = setInterval(() => {
console.log("中断请求");
xmlHttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery-ajax</title>
<script src="myAjax.js"></script>
<script>
window.onload = () => {
let oBtn = document.querySelector("button");
oBtn.onclick = () => {
ajax({
type: "post",
url: "ajax-jquery.php",
data:{
"userName": "BNTang",
"userPwd": "123456"
},
timeout: 3000,
success: (msg) => {
alert(msg.responseText);
},
error: (xhr) => {
alert(xhr.status);
}
});
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
本文主要就是博主编写了一个小小的一个案例并且遗留了一个问题首先先来看案例代码如下:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax练习</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 50px auto;
text-align: center;
background: #ccc;
}
img {
width: 200px;
height: 200px;
display: block;
margin: 10px auto 10px;
border: 1px solid #000;
}
p {
text-align: center;
background: pink;
}
</style>
<script src="myAjax.js"></script>
<script>
window.onload = function (ev) {
// 1.获取需要设置的元素
let oTitle = document.querySelector("#title");
let oDes = document.querySelector("#des");
let oImg = document.querySelector("img");
// 2.获取所有按钮
let oButtonList = document.querySelectorAll("button");
// 3.给按钮添加点击事件
oButtonList[0].onclick = function () {
// 4.发送Ajax请求到服务器
ajax({
type: "get",
url: "ajax-test.php",
data: {"name": this.getAttribute("name")},
timeout: 3000,
success: function (xhr) {
let res = xhr.responseText.split("|");
oTitle.innerHTML = res[0];
oDes.innerHTML = res[1];
oImg.setAttribute("src", res[2]);
},
error: function (xhr) {
alert(xhr.status);
}
});
}
oButtonList[1].onclick = function () {
}
oButtonList[2].onclick = function () {
}
}
</script>
</head>
<body>
<div>
<p id="title">商品标题名称</p>
<img src="" alt="">
<p id="des">商品描述信息</p>
<button name="nz">女装</button>
<button name="bb">包包</button>
<button name="tx">拖鞋</button>
</div>
</body>
</html>
ajax-test.php:
<?php
// 1.定义字典保存商品信息
$products = array(
"nz" => array("title" => "甜美女装", "des" => "人见人爱,花间花开,甜美系列", "image" => "../images/1.jpg"),
"bb" => array("title" => "奢华驴包", "des" => "送女友,送情人,送学妹,一送一个准系列", "image" => "../images/2.jpg"),
"tx" => array("title" => "键盘拖鞋", "des" => "程序员专属拖鞋, 屌丝气息浓郁, 你值得拥有", "image" => "../images/3.jpg")
);
// 2.获取前端传递的参数
$name = $_GET["name"];
// 3.根据前端传入的key,获取对应的字典
$product = $products[$name];
// 4.将小字典中的内容取出来返回给前端
echo $product["title"];
echo "|";
echo $product["des"];
echo "|";
echo $product["image"];
测试结果:
那么遗留的问题就是,博主在 php 后端使用 |
来进行分割返回给前端有没有什么弊端,如果你觉得有,那么是为什么,可以在下方评论区留言,下一篇文章我将会带着这个文章可以延伸出一个新的知识点哦。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。