php - PHP JSON 重定向
问题描述
我有一个注册表单,我想在注册成功(200)响应后重定向用户"location" => "home.php"
或通过 json 在 400(错误请求)上显示错误
我只知道一些 php 的基础知识,所以这应该是什么样子
--> register.php
?
结合下面的例子?
// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage
$errors = []; // collect errors in here
// do whatever you need to do with the $_POST / $_FILES data...
// capturing errors example...
if ($_POST['cpassword'] != $_POST['password']) {
$errors[] = "Passwords do not match!";
}
// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
if (count($errors)) {
header("Content-type: application/problem+json");
http_response_code(400);
exit(json_encode([
"message" => "Invalid form data or something",
"errors" => $errors
]));
}
header("Content-type: application/json");
exit(json_encode(["location" => "home.php"]));
}
// just a normal request, respond with redirects or HTML
// ...
foreach ($errors as $error) : ?>
<div class="error"><?= $error ?></div>
<?php endforeach;
客户端可以在成功时导航到主页或显示错误信息
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {
accept: "application/json", // let PHP know what type of response we want
},
body
})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})
请理解我是新手,我无法解决这个问题,
完整的 php 答案将有助于并标记为已解决
解决方案
当 JSON 包含重定向位置时,您在 JSON 中没有任何ok
元素。所以改变
exit(json_encode(["location" => "home.php"]));
至
exit(json_encode(["ok" => true, "location" => "home.php"]));
推荐阅读
- css - 是否有可能只有当它是其他元素的最后一个子元素时才选择类的 scss 选择器?
- reactjs - 如何将 useSelector 移动到分离文件并从中导入?
- microsoft-graph-api - how to create a meeting in English using graph api
- python - git : automatic action after successful merge on master
- html - 防止 SVG SMIL 点击动画多次运行
- python - 仅在完成购买后削减训练和验证数据
- android - DJI 电池电量耗尽
- java - 传递闭包和 Warshall 算法
- pandas - 如何将两个不同的训练有素的 ML 模型组合为一个?
- flutter - 只允许输入 3 位小数颤动