Home >Backend Development >PHP Tutorial >How to run JavaScript code in PHP? (code example)

How to run JavaScript code in PHP? (code example)

青灯夜游
青灯夜游Original
2019-01-16 17:48:3218282browse

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.

How to run JavaScript code in PHP? (code example)

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 &#39;<script type="text/javascript">&#39;;
echo &#39;alert("php中文网");&#39;;
echo &#39;</script>&#39;;
?>

Output:

How to run JavaScript code in PHP? (code example)

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:

How to run JavaScript code in PHP? (code example)

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:

How to run JavaScript code in PHP? (code example)

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!

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

Related articles

See more