n92*_*n92 35 javascript php forms
点击提交按钮,我有一个表单:
这是我的代码
<?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>
Run Code Online (Sandbox Code Playgroud)
但是无法提交表单,如果我在onClick上调用javascript代码,它就可以工作.这段代码中的问题是什么,有什么解决方法吗?
ket*_*o23 59
只需在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>
";
}
?>
Run Code Online (Sandbox Code Playgroud)
最近我发现了另一种将 JS 代码放入 PHP 代码的方法。它涉及 Heredoc PHP 语法。我希望它会对某人有所帮助。
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
Run Code Online (Sandbox Code Playgroud)
关闭 heredoc 结构后, $script 变量包含您可以像这样使用的 JS 代码:
<script><?= $script ?></script>
Run Code Online (Sandbox Code Playgroud)
使用这种方式的好处是现代 IDE 可以识别 Heredoc 中的 JS 代码并正确突出显示它,而不是使用字符串。而且您仍然可以在 JS 代码中使用 PHP 变量。
您可以像这样放置所有JS,因此在HTML准备好之前它不会执行
$(document).ready(function() {
// some code here
});
Run Code Online (Sandbox Code Playgroud)
记住这是jQuery,所以将它包含在head部分中.另请参阅为什么要使用jQuery而不是onload