php - 使用带有随机 ID 的 PHP 标头打开页面适用于 Edge,但不适用于 chrome
问题描述
我正在尝试生成一个随机数(1 - 151 之间),以便我可以根据随机生成的 ID 打开一个页面。这里的问题在于浏览器兼容性,因为预期的功能适用于 Edge,但不适用于 Chrome 或 FireFox。
pokedex.php:
<form action='randomPokemon.php' >
<button type="submit" class="toolsBtn">Random</button>
</form>
随机口袋妖怪.php:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'pokedex.php?pid=';
$randomid = rand(1, 151);
header("HTTP/1.1 303 See Other");
header("Location: http://$host$uri/$extra" . mt_rand(1, 151));
unset($randomid);
exit;
?>
现场演示: http: //fraserprovan.co.uk/projects/pokedex/pokedex.php
我不知道为什么它适用于 Microsoft Edge 而不是其他浏览器。在 chrome 上,它每次都会打开相同的页面,就好像变量 $randomid 没有改变一样。任何建议或其他资源的链接将不胜感激。
更新:决定用 Javascript 代替使用以下函数,感谢您的建议。
function randomPokemon(){
var randomNum = Math.floor(Math.random() * 151) + 1;
document.location.replace('pokedex.php?pid=' + randomNum);
}
解决方案
尝试使用绝对URI,也不要在 header-statement 之前留下任何空格或换行符。请参阅php-docs中的此注释
笔记:
大多数当代客户端接受相对 URI 作为 » Location: 的参数,但一些较旧的客户端需要一个绝对 URI,包括方案、主机名和绝对路径。您通常可以使用 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF'] 和 dirname() 自己从相对的 URI 中创建绝对 URI:
<?php /* Redirect to a different page in the current directory that was requested */ $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $extra = 'mypage.php'; header("Location: http://$host$uri/$extra"); exit; ?>
推荐阅读
- xml - XSLT 变量在 xsl:value-of select= 中不起作用
- nginx - GeoIP.dat.gz 和 GeoLiteCity.dat.gz 不再可用?获取 404 尝试加载它
- javascript - Google 地图 API 找不到 $(document).ready 中定义的回调
- ios - 如何为除某些特定配置之外的所有构建配置安装 pod?
- dart - 如何使用 Flutter SQFlite 获取数据库表中的行数
- ios - 在堆栈视图中点击按钮时未调用操作
- sql - 汇总SQL中列不同的所有行?
- ios - Swift - 使用 DispatchGroup() 从 Firebase Firestore 异步下载数据时出现问题
- elasticsearch - 作为分片和索引的函数,我们需要多少数据节点
- python - Tkinter RSS Ticker 在每次更新时加速