dswmmvrg40957 2019-03-02 00:56
浏览 250
已采纳

使用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); 
});
  • 写回答

2条回答 默认 最新

  • dongwang3066 2019-03-02 01:14
    关注

    You can try this in your php file:

    $response = [ message => "the message", success => true ];
    
    echo json_encode($response);
    

    You will receive a JSON response which you will use it to validate if the request was successful.

    In your javascript code, you have to parse this JSON response to an literal object like:

    fetch(url, {params})
     .then(response => response.json())
     .then((response) => {
       if (response.success) {
         // fetch was succesfull! 
       } else {
         // response.message could be used to show what was wrong
         throw new Error(response.message);
       }
      })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题