提交表单时,我尝试(回显)从 PHP 调用 javascript 函数。我遇到一个错误,函数未定义
。我确实知道 PHP 在 Javascript 之前加载,因此,该函数没有在 PHP 调用中定义。
我什至可以在 HTML 部分中创建 onclick
但下面的示例是一个更大程序的一部分,PHP 脚本位于一个单独的文件中,该文件包含在 HTML 页面的顶部,该函数调用时也会接收不同的参数并执行不同的操作,这将是一个AJAX函数。另外,我在页面渲染时加载了一些变量,我只想在程序中的某个点调用 JS 函数。将 PHP 移动到底部并不优雅,因为我必须在顶部添加一些 PHP,在底部添加一些 PHP 才能包含所有变量。
有没有办法将 PHP 部分包含在顶部,并且在需要时仍然使用一系列参数调用 AJAX 函数?或者更好的是,做这种事情的最佳方法是什么?我相信通过 PHP 回显 javascript 并不是最佳实践。
<?php
if (isset($_POST['a'])) {
echo "<script type='text/javascript'>example('hello');</script>";
echo "<script type='text/javascript'>printSome(0,0);</script>";
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="text">
<input type="submit" name="a">
</form>
</body>
<script type='text/javascript'>
function example(variable)
{
window.alert(variable);
}
function printSome(type, quantity)
{
return $.ajax({
url : 'http://localhost/printDoc.php',
type : 'POST',
dataType : 'json',
data : {
DTStype : type,
DTSquantity : quantity
},
cache : false
});
}
</script>
</html>
最佳答案
试试这个
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="text">
<input type="submit" name="a">
</form>
</body>
<script type='text/javascript'>
function example(variable)
{
window.alert(variable);
}
</script>
<?php
if (isset($_POST['a'])) {
echo "<script type='text/javascript'>example('hello');</script>";
}
?>
</html>
关于javascript - 在 PHP 验证之前加载 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47264002/