从 php 调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12812842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:32:18  来源:igfitidea点击:

calling javascript function from php

phpjavascriptfunction

提问by user1334130

I am trying to call a javascript function from php. According to all of the examples I have been looking at the following should work but it doesn't. Why not?

我正在尝试从 php 调用 javascript 函数。根据我一直在查看的所有示例,以下内容应该有效,但无效。为什么不?

 <?php
    echo "function test";
    echo '<script type="text/javascript">    run();      </script>';
?>

<html>
    <script type="text/javascript">
        function run(){
            alert("hello world");
        }
    </script>
</html>

回答by Upvote

Your html is invalid. You're missing some tags.

您的 html 无效。你缺少一些标签。

And you need to call the function after it has been declared, like this

并且您需要在声明后调用该函数,如下所示

<html>
    <head>
       <title></title>

       <script type="text/javascript">
            function run(){
                alert("hello world");
            }

           <?php
               echo "run();";
           ?>
       </script>

    </head>
    <body>
    </body>
</html>

In this case you can place the run before the method declaration, but as soon as you wrap the method call inside another script tag, the script tag has to be after the method declaration.

在这种情况下,您可以将运行放在方法声明之前,但是一旦将方法调用包装在另一个脚本标记中,脚本标记就必须在方法声明之后。

Try yourself http://jsfiddle.net/qdwXv/

试试自己http://jsfiddle.net/qdwXv/

回答by NullPoiиteя

the function must declare before use
it should be

函数必须在使用前声明
它应该是

<html>
    <script type="text/javascript">
        function run(){
            alert("hello world");
        }
       <?php
       echo "function test";
        echo   run();      ;
     ?>
    </script>
</html>

回答by Thom Porter

As others have suggested, the function needs to be declared first. But, if you need to echo out the JavaScript from PHP first, you can either store it in a PHP variable to echo out later, or have your code wait for the dom to finish loading first...

正如其他人所建议的那样,需要首先声明该函数。但是,如果您需要先从 PHP 中回显 JavaScript,您可以将其存储在 PHP 变量中以便稍后回显,或者让您的代码等待 dom 首先完成加载......

document.ready = function() {
    run()
  }

If you're using jQuery or another framework, they probalby have a better way of doing that... In jQuery:

如果你使用 jQuery 或其他框架,他们可能有更好的方法来做到这一点......在 jQuery 中:

$(function(){
   run();
})