前后端数据交互:fetch:api
1.前端代码
<!-- 用户登录 -->
<form class="login" id="login">
<table>
<caption>
用户登录
</caption>
<tbody>
<tr>
<td><label for="email">邮箱:</label></td>
<td><input type="email" name="email" id="email" /></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td colspan="2"><button type="button" onclick=check(this)>提交</button></td>
</tr>
</tbody>
</table>
</form>
<p>
<a href="register.html">没有帐号,请先注册</a>
</p>
</main>
<script>
async function check(btn) {
//email
const email = btn.form.email.value.trim();
//password
const password = btn.form.password.value.trim();
//非空验证
if (email.length > 0 && password.length > 0) {
//异步提交:fetch api
const response = await fetch('./lib/user/login.php', {
//请求类型:post
method: 'POST',
//请求头
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
//数据
body: JSON.stringify({
email,
password
})
});
//2.解析数据
const data = await response.json();
console.log(data);
} else {
alert('邮箱或密码不能为空');
return false;
}
}
</script>
2. 后端代码
<?php
//获取登录数据
// print_r($_POST);
//不行,因为不是通过传统的表单格式提交,用的是JSON
//json当成文本原始数据流来接收
$json = file_get_contents('php://input');
// $json 并非PHP能识别的数据类型,它只是json格式的字符串
// $json -> php.array, true:数组
$user = json_decode($json,true);
//验证
//这里暂不处理
//返回:php.string -> json 返回,前端只认识json
// echo json_encode('验证成功');
echo json_encode($user);
`
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!