HTML重定向到根目录


HTML Redirect To Root

我了解如何获得要重定向的页面:

<meta http-equiv="refresh" content="10; url=http://example.com/" />

我需要10-20秒的延迟(如上所示),让我的访问者看到他们的数据被成功收集。

我们有以下网站:

  • 本地PC:http://localhost
  • 员工测试:http://dev.example.com
  • 客户BETA:http://beta.example.com
  • 实时:http://www.example.com

显然,我不想在我的电脑工作后更改代码,使其在员工测试环境中工作,我们在测试版发布时再次更改代码,或者在上线前再次更改代码。

与上面的重定向一样,重定向将在有人在我们的网站上提交表格后使用。

如何创建一个知道其位置的重定向

我目前的任务是找出如何在PHP中做到这一点,这样我就可以在页面提供之前编写标记了。

但是,我也为其他客户开发ASP.NET页面,所以我想看看在Windows中也可以处理的方法。

更改重定向标记以指向url /,该url将始终是您所在域的根路径。

<meta http-equiv="refresh" content="10; url=/" />

在PHP中:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('location: /'); //or header('location: '.$_SERVER['HTTP_HOST']);
}

带有jQuery setTimeout功能:

setTimeout(function(){ window.location = '/'; }, 10000);  //10.000 milliseconds delay

在这里,您可以了解更多关于PHP SERVER超级全局的信息,并通过此链接访问PHP header()函数。

使用ajax向服务器发送请求

如果您使用jQuery,您可能应该考虑这个解决方案:通过ajax请求PHP文件,并进行数据库更新或一些服务器端的工作。如果成功,则显示一条消息并在一段时间后重定向。

示例:

jQuery:

$('#form').on('submit', function() {
    var inputs = $(this).serialize(); //safe the submitted data
    $.post('path_to_file.php', inputs, function(data) {  //returned a json array
        var data = $.parseJSON(data);  //decode the json data
        if('errors' in data) {  //were there any errors?
            $.each(data['errors'], function() {
                $('#error-box').append(this); //show the error message
            });
        } else {  //if no errors
            $('#succes-box').html('Update was successful.');
            setTimeout(function(){ window.location = '/'; }, 10000); //Redirect after 10s
        }
    });
});

path_to_file.php

<?php
//Do something with post data.....
$response = array();
if(!$query) {
    $response['errors'][] = 'There was an error querying the database.';  //error example
}
echo json_encode($response);

希望这能有所帮助。