calling javascript function from php

2020-07-08 08:14发布

问题:

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
    echo "function test";
    echo '<script type="text/javascript">    run();      </script>';
?>

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

回答1:

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

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/



回答2:

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>


回答3:

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...

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

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

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