Home >Backend Development >PHP Problem >Can js be executed in php script?
JS cannot be executed in PHP scripts. JS can only be executed after PHP is parsed into HTML. If you want to use PHP to output JS, you need to output the JS code as a PHP string.
The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
Can js be executed in a php script?
Js cannot be executed in php. JS can only be executed after php is parsed into html. If you want to use php to output js, you must output the js code as a php string.
Example 1: Writing JavaScript code inside PHP code
<?php header("content-type:text/html;charset=utf-8"); echo '<script type="text/javascript">'; echo 'alert("hello world!");'; echo '</script>'; ?>
Output:
Example 2: Writing JavaScript outside PHP code Code (in the same PHP file)
<?php header("content-type:text/html;charset=utf-8"); //php代码 ?> <script type="text/javascript"> alert("hello"); </script>
Output:
Example 3: JavaScript Function - DOM Manipulation (in the same PHP file)
<?php echo "<div id='demo'></div>"; ?> <script type="text/JavaScript"> // 调用函数 var x = myFunction(11, 10); document.getElementById("demo").innerHTML = x; // 函数返回a和b的乘积 function myFunction(a, b) { return a * b; } </script>
Output:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Can js be executed in php script?. For more information, please follow other related articles on the PHP Chinese website!