使用Fetch在PHP成功后重定向页面

I'm creating a registration system for a university project. This is using fetch to post the data from the form to a PHP file.

I want to transfer over a $message variable that is echoed at the bottom of my PHP page to know if the registration has been successful, or if an error message has occurred. If I can see that the $message equals my success string, I think I can do an if statement using window.location.href like below? Currently it is redirecting the page for any successful fetch, no matter what the response from PHP is.

I've tried using header("Location: /index.html"); in my PHP file on the success line, but this also didn't work for me. I've spent hours looks for a solution but I really can't get my head around how to pass this variable over.

var myJSON = JSON.stringify(userDetails);

fetch("url/register.php", {
    method: "POST",
    mode: "no-cors", 
    cache: "no-cache", /
    credentials: "same-origin", 
    headers: {
        "Content-Type": "application/json"
    },
    redirect: "follow", 
    referrer: "no-referrer", 
    body: myJSON 
}).then((response) => {
    if (response.ok) {
        return response.blob();
    } else {
        throw new Error("Things went poorly.");
    }
}).then((response) => {
    //Fetch was successful!
    window.location.href = "url/index.html";
}).catch((error) => {
    console.log(error); 
});
查看全部
dswmmvrg40957
dswmmvrg40957
2019/03/02 00:56
  • variables
  • fetch
  • php
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复