我在网站的 DoStuff.php 文件中有一个 PHP 变量 thePHPvar。 thePHPvar 被设置为一个字符串。
然后 DoStuff.php 中的代码执行
header("Location: http://localhost/theWebite/index.php");
我需要在 index.php 的 body 标签内的 onLoad 处理程序中做两件事:
<body onload="doLoad()">
我的 doLoad() 函数必须能够做两件事:
2) 此外,doLoad() 必须能够检测到“thePHPvar”何时为空,从而避免尝试使用 'thePHPvar' 并跳过使用该字符串的逻辑。
我是 php 和 javascript 的新手,我对现在的工作印象深刻, 但我已经花了 1/2 天的时间,阅读了很多关于 SO 的类似问题。
我必须能够重定向回 index.php,获取此字符串变量,如果已设置(非空),则执行一些 javascript 代码。
现在这就是我的 onLoad() 所做的一切,嘿——它起作用了。但还不是正确的方法。
<head>
<script type="text/javascript">
function doLoad()
{
alert("Page is loaded");
}
</script>
</head>
如果不介绍我必须学习的一堆新东西,比如 Ajax 等,我怎样才能用 javascript、html、php 和我这里的东西来完成它?
最佳答案
您可以使用 session variable正如豪尔赫所说,如果这个 myPHPVar 是特定于用户的。否则,在标题重定向中传递变量:
header("Location: http://localhost/theWebite/index.php?myVar=" . $myPHPVar);
作为初学者,您可能不想使用 JSON 将变量从 PHP 获取到 Javascript,但如果您必须将大量数据传递给 Javascript 代码,请务必查找它。
<script>
var myPHPVar="<?php echo $_GET['myVar']; ?>";
</script>
如果用户对该 PHP 变量有任何影响,请务必 sanitise the variable against XSS attacks.
要在您的 doLoad
方法中检查 myPHPVar 是否为空,只需使用 if (!myPHPVar) { .... }
关于php - 需要从 PHP header() 重定向将变量传递给 OnLoad(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529413/