[英]how to write javascript code inside 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.