首页 > 解决方案 > PHP header('location: index.php') 工作但不显示

问题描述

我提前为我糟糕的英语道歉。

当 php 脚本验证数据时,我实际上是在尝试在我的主页上重定向某人。

我的验证脚本

/* validate the data retrieved from the $ _POST (only php, nothing else)
** [...]
** returning an assoc array like this ['flag' => <true or false>, 'message' => "my error message"]
*/

if ($error['flag']) {
    header('Content-Type: application/json;charset=utf-8');
    echo(json_encode($error));
}
else {
    header('location: index.php');
    exit();
}

我的 js 函数来发送我的数据

// Triggered by button onclick()
function createPost() {
    const URL = "./postFilter.php?submit=create";
    const form = document.getElementById('form_create_post');

    let formData = new FormData(form);

    let xhttp = new XMLHttpRequest();
    //Response
    xhttp.onreadystatechange = function() {
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
            error = JSON.parse(this.responseText);
            if (error['flag']) {
                document.getElementById("errorMsg").innerHTML = error['message'];
                document.getElementById("form-alert").style.display = "block";
            }
        }
    };
    xhttp.open("POST", URL, true);
    xhttp.send(formData);
}

这是我得到的 网络瀑布 https://i.stack.imgur.com/NR2cE.png 网络第一个请求标头 https://i.stack.imgur.com/mTnk3.png 网络第二个请求标头 https://i .stack.imgur.com/SJbsN.png

我不明白我的代码是否出错以及为什么我没有被重定向到 index.php 而我实际上收到了 index.php

标签: javascriptphpxmlhttprequest

解决方案


推荐阅读