如何从php调用javascript函数脚本


<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>
<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script  type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>

这段代码被大大简化了,但是给出了关键值。我试图在php代码的底部运行一个Javascript函数。在完整的代码中,php在发生某些情况时回显该脚本。我试过类似的代码:

echo "<script> alert('Error!') </script>";

这工作,但我宁愿创建我自己的警告消息,发生在页面的右上角。div设置为display: none,但我试图运行调用设置display: block的函数。所有的css处理,我已经测试了它的工作与一个按钮。

我在XAMPP apache mysql上运行我的代码。这是加载页面时的错误类型:

Uncaught ReferenceError: error_warning is not defined
at account.php:1

我所收集的是,作为php运行服务器端,该函数没有定义,所以它不能看到它因此返回错误。我试过几个解决方案,比如把脚本放在php之前,他们没有工作。

有人能帮忙吗?

感谢

解决这个问题的方法是…

  1. 定义后调用函数

为此,您可以使用一些服务器端变量来激活页面末尾的函数调用。

<script> function popAlert(errorType){//do something} </script>
<?php if($error == 1) echo "<script>popAlert(1);</script>";?>
  1. 把你的函数放在一个单独的.js文件中,并包含在你的页面中
<?php 
if($error == 1) echo "<script>popAlert(1);</script>";
?>
<script src="errors.js"></script> 
  1. 使用Ajax从.php文件获取响应,然后确定需要弹出的内容

例:-

$.post("url", "data", function(data, status){
if(status == "success"){
if(data == 1) popAlert(1);
if(data == 2) popAlert(2);
}
});

我建议你使用出汗警报在这里引用

交货:-

function popAlert(type){
if(type == 1){
Swal.fire({
icon: 'success',
title: 'You did it...!'
})
}
if(type == 2){
Swal.fire({
icon: 'error',
title: 'Oops, something went wrong...!'
})
}
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.10.1/dist/sweetalert2.all.min.js"></script>
<h1>Click on buttons to pop alert</h1>
<button onclick='popAlert(1)'> success </button><br/>
<button onclick='popAlert(2)'> error </button><br/>

对于任何查询注释下来。

有多个选项可以这样做。Ajax或简单的echo。但是对于您的问题,只需将onload函数添加到脚本echo中就足够了。

<?php
echo "<script type='text/javascript'>window.onload = () => {error_warning('Error!')}; </script>";
?>

另一种可能的选择是在函数声明后调用它。

<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script  type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>
<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>