Home >Backend Development >PHP Tutorial >How to run JavaScript code in PHP? (code example)
JavaScript is a client-side scripting language, and PHP is a server-side scripting language used to interact with databases. So how do you run JavaScript in PHP? This article will introduce you to several methods of running JavaScript in PHP. I hope it will be helpful to you.
In PHP, HTML code and JavaScript code will be treated as strings and then parsed in the browser. Below we use code examples to introduce the method of running JavaScript in PHP. [Related video tutorial recommendations: PHP tutorial, JavaScript tutorial]
Example 1: Writing JavaScript code in PHP code
<?php header("content-type:text/html;charset=utf-8"); echo '<script type="text/javascript">'; echo 'alert("php中文网");'; echo '</script>'; ?>
Output:
Example 2: Writing JavaScript code outside of PHP code (in the same PHP file)
<?php header("content-type:text/html;charset=utf-8"); //php代码 ?> <script type="text/javascript"> alert("欢迎来到php中文网"); </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:
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to run JavaScript code in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!