我试图根据访问者的年龄显示不同的iframe,而不需要重定向/刷新。
然而,在验证访问者年龄后,javascript没有被正确应用,或者根本没有被应用。
我总是以一个空白的iframe结束。有人请看一下我下面的代码:
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script></head>
<form method="post">
<input type="date" name="dob"><br>
<input type="submit" name="submit" value="Verify Age" />
</form>
<?php
$minAge = 18; // You might read this from a file/database.
$minAge *= 3600*24*365.25; // $minAge in seconds
if(isset($_POST['submit'])){
$birth_date = strtotime($_POST['dob']);
$now = strtotime("now");
$age = $now - $birth_date; // age is in seconds
if($age > $minAge)
echo '<script>$("#myiframe").attr("src", "http://URL1.com");</script>';
else
echo '<script>$("#myiframe").attr("src", "http://URL2.com");</script>';
} ?>
<iframe id="myiframe"></iframe>
</html>
在将iframe
添加到DOM之前,js正在启动。您可以将php代码(至少是渲染,即echo
)移动到iframe
标记下,或者使用类似$(document).ready(function(){<...>})
的东西。顺便说一下,还有一种更优雅的方式:
<?php
$minAge = 18; // You might read this from a file/database.
$minAge *= 3600*24*365.25; // $minAge in seconds
if(isset($_POST['submit'])){
$birth_date = strtotime($_POST['dob']);
$now = strtotime("now");
$age = $now - $birth_date; // age is in seconds
?>
<iframe id = "myiframe"
src = "<?php echo ($age > $minAge ? 'http://URL1.com' : 'http://URL2.com'); ?> ">
</iframe>
<?php } ?>
当脚本运行时,DOM还没有呈现iframe。您需要将您的iframe移动到呈现脚本标记的php代码段之上。