繁体   English   中英

如何从php调用javascript函数脚本

[英]How to call a javascript function script from php

<?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 或简单的回声。 但是对于您的问题,只需将 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>";

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM