如何解决无法使用 _GET 获取 URL 参数
第一次发帖,我在使用 PHP 方面还很陌生,所以请不要打扰我。如果这需要进一步解释,请告诉我。
我有一个页面(我们称之为 page1.PHP),其中声明了以下全局变量:
$online = true;
当点击 page1.PHP 上的链接时,我想将一个参数(称为 方法)传递到下一页(我们称之为 page2.PHP)。 PHP)。如果专门通过 page1.PHP 中的链接访问 page2.PHP,我希望它加载此参数并触发特定行为。
更新:21 年 3 月 16 日添加
page1.PHP 上的链接包含在一个用于多个页面的模板文件中。因此,如果页面具有 $online = true
的全局变量,我使用了 PHP if 语句将参数附加到链接:
<a href="page2.PHP<?PHP if(isset(GLOBALS['online'])) {?>?method=online<?PHP } ?>"?link</a>
到目前为止,我已经成功(我认为)将参数传递给 page2.PHP (page2.PHP?method=online)。在 page2.PHP 的顶部,我使用以下代码将此参数的值分配给名为 $method
的变量:
$method = $_GET['method'];
我预计这会产生 $method = "online"
但不幸的是,当我这样做并尝试 echo $method
时,我收到以下通知:
注意:未定义索引:方法在 C:URL\index.PHP 上 第 7 行
当我开始时,这似乎相当简单,但这让我发疯。我错过了什么?提前致谢!
解决方法
这种方式对我有用:
page1.php
<!DOCTYPE html>
<html>
<body>
<a href="page2.php?method=online">link</a>
</body>
</html>
page2.php
<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
$method = false; // empty
if(array_key_exists('method',$_GET) and !empty($_GET['method']))
$method = $_GET['method'];
var_dump($method);
// https://yoururl/page2.php?method=online
// string(6) "online"
// https://yoururl/page2.php?method=
// bool(false)
// https://yoururl/page2.php
// bool(false)
,
像这样更新你的代码
// if it does not exist.
$method = $_GET['method'] ?? null;
PHP Null coalescing operator
不断尝试和玩弄语言,你的方向是正确的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。