簡體   English   中英

如何在php中編寫javascript代碼

[英]how to write javascript code inside php

我有一個表格,點擊提交按鈕:

  1. 我想在同一個文件中做一些任務(數據庫任務)和
  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 代碼,它可以工作。此代碼有什么問題,是否有任何解決方法

只需在 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>
        ";
     }
  ?>

最近我發現了另一種將 JS 代碼放入 PHP 代碼的方法。 它涉及 Heredoc PHP 語法。 我希望它會對某人有所幫助。

<?php
$script = <<< JS

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

JS;
?>

關閉 heredoc 結構后, $script 變量包含您可以像這樣使用的 JS 代碼:

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

使用這種方式的好處是現代 IDE 可以識別 Heredoc 中的 JS 代碼並正確突出顯示它,而不是使用字符串。 而且您仍然可以在 JS 代碼中使用 PHP 變量。

您可以像這樣放置所有 JS,因此它不會在您的 HTML 准備好之前執行

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

請記住這是 jQuery,因此將其包含在 head 部分中。 另請參閱為什么您應該使用 jQuery 而不是 onload

在執行腳本時,按鈕不存在,因為 DOM 未完全加載。 最簡單的解決方案是將腳本塊放在表單之后。

另一種解決方案是捕獲window.onload事件或使用jQuery 庫(如果您只有這一個 JavaScript,那就大材小用了)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM