javascript - php 不是 "echo-ing"javascript 正确

标签 javascript php jquery html iframe

我正在尝试根据访问者的年龄显示不同的 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>

最佳答案

你的 js 在 iframe 之前开火了被添加到 DOM 中。您可以在 echo 下移动您的 PHP 代码(至少是渲染,即 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 } ?>

关于javascript - php 不是 "echo-ing"javascript 正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29480235/

相关文章:

php - Yii 自动数据库迁移

javascript - 在html中单击后创建onClick内容

PHP while 循环

javascript - 在 Ajax 调用期间停止通过按钮单击/页面更改进入错误函数

javascript - 字符串匹配(Javascript)

javascript - Worker.onmessage 后的 angular2 变化检测未按预期工作

php - 如何在 wamp 上运行套接字以及本地主机使用哪个端口

javascript - 如何通过 `echo json_encode($data);`获取所有数据

jquery - CSS 样式不适用于 jquery 弹出窗口

javascript - typescript 错误 : Type 'string' is not assignable to type for Typography