Home >Backend Development >PHP Problem >Can js be executed in php script?

Can js be executed in php script?

藏色散人
藏色散人Original
2021-06-21 09:50:453918browse

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.

Can js be executed in php script?

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 &#39;<script type="text/javascript">&#39;;
echo &#39;alert("hello world!");&#39;;
echo &#39;</script>&#39;;
?>

Output:

Can js be executed in php script?

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:

Can js be executed in php script?

Example 3: JavaScript Function - DOM Manipulation (in the same PHP file)

<?php 
    echo "<div id=&#39;demo&#39;></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:

Can js be executed in php script?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn