PHP混排——js使用PHP变量示例
效果图
代码示例
<?php
$arr = [
[
'name' => '小明',
'age' => 18
],
[
'name' => '小张',
'age' => 17
],
[
'name' => '小李',
'age' => 15
],
];
$message = '我是来自PHP的变量';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js使用PHP变量混排写法</title>
</head>
<body>
<script>
// PHP数组的使用方法:直接使用PHP返回的json格式数据
var arr = <?php echo json_encode($arr); ?>;
console.log(arr);
for (var i = 0; i < 3; i++) {
document.write(arr[i].name + "<br>" + arr[i].age + "<hr>");
}
//变量的使用方法
var str = '<?php echo $message?>';
console.log(str);
document.write("php变量的使用:" + str+ "<hr>");
</script>
</body>
</html>
注意:PHP的数组在JavaScript或JQuery中需要先转成JSON字符串后再使用,若js中直接使用PHP数组会报语法错误