【问题标题】:how to write javascript code inside php如何在php中编写javascript代码
【发布时间】:2012-05-22 16:45:20
【问题描述】:

我有一个表单,点击提交按钮:

  1. 我想在同一个文件中执行一些任务(db 任务)并且
  2. 我希望通过重定向将表单数据发送到 test.php

这是我的代码

    <?php
    if(isset($_POST['btn'])){
        //do some task
    ?>
    <script type="text/javascript">
        var e = document.getElementById('testForm'); e.action='test.php'; e.submit();</script>
    <?php
    }
    ?>
<form name="testForm" id="testForm"  method="POST"  >
    <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>

但无法提交表单,如果我在 onClick 上调用 javascript 代码,它可以工作。这段代码有什么问题,是否有任何解决方法

【问题讨论】:

  • 非常合乎逻辑,您的 javascript 在浏览器中输出的那一刻运行并打印您的表单......之后。您应该将代码包含在 window.onload 事件侦听器中,以便仅在页面加载完成后执行。

标签: php javascript forms


【解决方案1】:

只需在 if 函数中回显 javascript

 <form name="testForm" id="testForm"  method="POST"  >
     <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>
 <?php
    if(isset($_POST['btn'])){
        echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
            </script>
        ";
     }
  ?>

【讨论】:

  • 请注意这里的解决方案是 not 使用 PHP 生成 JavaScript 代码,但是 PHP 块出现在表单标签之后,这意味着 DOM 元素 'testForm' 是JavaScript 执行时初始化。
【解决方案2】:

最近我遇到了另一种将 JS 代码放入 PHP 代码的方法。它涉及 Heredoc PHP 语法。我希望它对某人有所帮助。

<?php
$script = <<< JS

$(function() {
   // js code goes here
});

JS;
?>

关闭heredoc构造后,$script变量包含你的JS代码,可以像这样使用:

<script><?= $script ?></script>

使用这种方式的好处是现代 IDE 可以识别 Heredoc 中的 JS 代码并正确突出显示它,这与使用字符串不同。而且你仍然可以在 JS 代码中使用 PHP 变量。

【讨论】:

  • 谢谢你给了我指导
【解决方案3】:

你可以把你所有的 JS 都这样放置,所以在你的 HTML 准备好之前它不会执行

$(document).ready(function() {
   // some code here
 });

记住这是 jQuery,所以将它包含在 head 部分中。另见Why you should use jQuery and not onload

【讨论】:

    【解决方案4】:

    在执行脚本时,按钮不存在,因为 DOM 未完全加载。最简单的解决方案是将脚本块放在表单之后。

    另一种解决方案是捕获window.onload 事件或使用jQuery library(如果你只有这一个JavaScript 就过分了)。

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2021-11-04
      • 2018-07-04
      相关资源
      最近更新 更多