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

使用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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!