首页 > 解决方案 > 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 答案将有助于并标记为已解决

标签: phpjqueryjson

解决方案


当 JSON 包含重定向位置时,您在 JSON 中没有任何ok元素。所以改变

    exit(json_encode(["location" => "home.php"]));

    exit(json_encode(["ok" => true, "location" => "home.php"]));

推荐阅读