Method 1: Use embedded PHP script tags
1. Simple splicing
Use the inline PHP script tag <?php ?>
to embed the value of the PHP variable $phpVariable
into the JavaScript code.
<?php
$phpVariable = "Hello, World!";
?>
<script>
// 将 PHP 变量的值传递给 JavaScript 变量
var jsVariable = '<?php echo $phpVariable; ?>';
// 在 JavaScript 中使用 jsVariable
console.log(jsVariable); // 输出:Hello, World!
</script>
Supplement: Processing when PHP variables are arrays
<?php
$phpVariable = ['这是数组第一项', '这是数组第二项'];
?>
<script>
// 将 PHP 变量的值传递给 JavaScript 变量
var jsVariable = '<?php echo $phpVariable[0]; ?>';
// 在 JavaScript 中使用 jsVariable
alert(jsVariable); // 输出:这是数组第一项
</script>
The above method can output individual items, but if replaced, it cannot be output correctly, as follows
<?php
$phpVariable = ['这是数组第一项', '这是数组第二项'];
?>
<script>
// 将 PHP 变量的值传递给 JavaScript 变量
var jsVariable = '<?php echo $phpVariable; ?>';
// 在 JavaScript 中使用 jsVariable
alert(jsVariable[0]); // 输出:A
</script>
The output result is the first value of Array.
Solution
通过
json_encode() converts a PHP array or object into a JSON string representationConvert a JSON-formatted string into a JavaScript object or array through JSON.parse().
<?php
$phpVariable = ['这是数组第一项', '这是数组第二项'];
?>
<script>
// 将 PHP 变量的值传递给 JavaScript 变量
var jsVariable = JSON.parse('<?php echo json_encode($phpVariable); ?>');
// 在 JavaScript 中使用 jsVariable
alert(jsVariable[0]); // 输出:这是数组第一项
</script>
2. Given a hidden text box to store the value
Store variables through text boxes in a <?php?>
<?php
if (isset($_SESSION['UserID'])) {
$sql = "
select depart_code
from www_users
where userid = '" . $_SESSION['UserID'] . "'
";
$result = DB_query($sql, $db);
if ($row = DB_fetch_array($result)) {
$departCode = $row['depart_code'];
echo "<input type='hidden' id='departCode' value='" . $departCode . "'>";
// echo "<script>alert('" . $departCode . "')</script>";
} else {
prnMsg(_('找不到相应数据!'), 'error');
}
}
?>
Get php variables in js
var departCode = document.getElementById('departCode').value;
alert(departCode);
Method 2: Use AJAX request
If you need to dynamically get the value of a PHP variable from the backend, you can use AJAX requests.
1. Page A
Use jQuery's $.ajax()
method to make a GET request to the backend PHP file and set JavaScript variables jsVariable
based on the returned data.
<!-- 引入 jQuery 库 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: 'get_php_variable.php', // 后端 PHP 文件的路径
method: 'GET',
success: function(response) {
var jsVariable = response; // 根据后端返回的数据设置 JavaScript 变量
console.log(jsVariable); // 输出从 PHP 获取的变量值
},
error: function() {
console.log('请求失败');
}
});
});
</script>
2. Page B
In the backend PHP file get_php_variable.php
you can get the value of the PHP variable and return it to the AJAX request if needed. For example:
<?php
$phpVariable = "Hello, World!";
$response = array('phpVariable' => $phpVariable); // 构造响应数据数组
echo $phpVariable;
?>