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數組會報語法錯誤