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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?