注册后PHP AJAX重定向



我有一个注册表单。PHP正在检查short password
AJAX会发出来自PHP的echo错误警报。

使用PHP,在if-else语句之后,
用户将被注册并成功重定向到index.php(良好(

header('Location:home.php');
exit;

问题是,如果出现任何错误,用户将被重定向到handler.php,并且回波警报显示在那里(白色页面上(

var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
if (xhr.status >= 200 && xhr.status <= 299) {
var response = JSON.parse(xhr.responseText);
if (response.location) {
window.location.href = response.location;
} else {
xhr.send(form_data);
}
}

示例2:警报将正确显示在<div class="msg"></div>位置
(但也会在警报所在的注册表上显示index.php(

var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
xhr.send(form_data);
};

因此,我希望用户重定向到index.php&还有AJAX 要处理的警报

关于用重定向响应AJAX请求,请参阅post-api调用和用post方法提交表单之间的区别是什么?。解释得比我做得好。

基本思想是,当异步调用时,PHP应该做它需要做的事情,并以200(成功(或400(坏请求(等错误状态+错误详细信息进行响应。

// 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
}
})

最新更新