【问题标题】:php not "echo-ing" the javascript correctlyphp没有正确“回显”javascript
【发布时间】:2015-06-11 09:06:46
【问题描述】:

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

【问题讨论】:

  • 等等...如果你用 PHP 做这个,你需要 PHP 做什么?为什么不只是echo '&lt;iframe src="http://URL1.com"&gt;&lt;/iframe&gt;';

标签: javascript php jquery html iframe


【解决方案1】:

当您的脚本运行时,DOM 还没有渲染 iframe。您需要将 iframe 移到呈现脚本标记的 php 代码段上方。

【讨论】:

    【解决方案2】:

    您的 js 在 iframe 添加到 DOM 之前触发。您可以在iframe 标记下移动您的php 代码(至少呈现,即echo)或使用$(document).ready(function(){&lt;...&gt;}) 之类的东西。顺便说一句,还有一种更优雅的方式:

    <?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 } ?>
    

    【讨论】:

    • 我从没想过!谢谢! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2023-03-21
    • 2017-07-29
    • 2014-04-23
    • 2011-07-10
    • 2012-02-23
    相关资源
    最近更新 更多