1.用POST请求给后端传递数据
代码
JS:
var xhr = new XMLHttpRequest();
xhr.open("POST", "post.php", true);
//application/x-www-form-urlencoded:设置传递参数时使用的编码格式(默认)
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');//设置请求头
var data = 'name=zs&age=18'; //数据格式:key1=val1&key2=val2
xhr.send(data); //post请求在send()中传递参数
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
PHP:
<?php
echo "hello world!!!!"
?>
结果
可以看到多了一个:表单数据(Form Data)的两行数据
(application/x-www-form-urlencoded)
改进
在后端接收POST请求发来的数据
PHP:
<?php
$name=$_POST['name'];
$age=$_POST['age'];
// echo $name;//zs
// echo json_encode([$name,$age]);//输出["zs","18"]
// 把关联数组[name,age]转化成JSON对象
echo json_encode([
'name'=>$name,
'age'=>$age
]);
?>
控制台输出:json字符串(特点:key带引号)
{"name":"zs","age":"18"}
若把获取返回响应信息的输出语句改为:console.log(JSON.parse(xhr.responseText));
将输出的是对象:
{name: 'zs', age: '18'}
age: "18"
name: "zs"
[[Prototype]]: Object
知识点
4.JSON.parse:json字符串=>对象
JSON.stringify:对象=>json字符串
5.vscode替换快捷键:CTRL+H
php:
1.$_POST:接收POST请求发送过来的data
2.关联数组:以键值对的形式作为数组元素
3.json_encode:数组=>json字符串
json_decode:json字符串=>数组
2.POST方式实现登录功能
代码
html:
<label for="">用户名:</label>
<input type="text">
<label for="">密码:</label>
<input type="text">
<input type="button" value="提交">
<script>
var [user, pwd, btn] = document.querySelectorAll("input"); //解构赋值
btn.addEventListener("click", () => {
// 编辑发送数据的格式
var data = 'user=' + user.value + '&pwd=' + pwd.value;
post('./postlogin.php', data); //调用post()
});
function post(url, data) {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
// 设置请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
</script>
php:
<?php
$user=$_POST['user'];
$pwd=$_POST['pwd'];
$u='张三';
$p=123;
if($user==$u&&$pwd==$p){
echo "正确";
}else{
echo "错误";
}
?>
结果
改进
把php的echo改一下,把js对应的接收语句也改一下
js:
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// console.log(xhr.response);
let res = JSON.parse(xhr.response);
// console.log(res);
if (res.status == 100) { // 登录成功
location.href = 'http://www.jd.com';
} else {
alert('失败')
}
}
}
php:
<?php
$user = $_POST['user'];
$pwd = $_POST['pwd'];
$u ='张三';
$p = 123;
$res = [];
if($user==$u && $pwd==$p){
$res = [
'status'=>100,
'msg'=>'Request Success',
'info'=>''
];}else{
$res = [
'status'=>101,
'msg'=>'Request Success',
'info'=>'密码和账户名不匹配'
];
}
echo json_encode($res);
?>
结果:
输入正确后自动跳转到jd