PHP把数据写入JSON文件
<?php
$data = array ();
$data ["fruit"] = "apple" ;
$data ["animal"] = "tiget";
$json_string = json_encode( $data );
?>
PHP读取JSON数据?
<?php
$str = file_get_contents ( 'one.json' );
$data = json_decode( $str , true);
print_r($data);
?>
js通过getElementByID获取PHP数据
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
<script type="text/JavaScript">
function test()
{
alert(document.getElementById("hid").value)
}
</script>
</head>
<body>
<?php
$data = array("fruit" => ["apple", "banana", "aa"], "animal" => "tiger"); // 定义一个数组
$data = json_encode($data); //转成json格式
?>
<form method="post" action="hh.php">
<input type="hidden" id="hid" name="hid" value="<?php print_r($data); ?>">
<input type="button" value="点击" οnclick="test()">
</form>
</body>
</html>
PHP向js传递数组
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function add(array) {
alert(array);
}
</script>
<?php
$arr = array('1', '2', '3', '4', '5');
$str = json_encode($arr);
echo "<input type='button' name='insert' value='点击' onClick='add($str)'>";
?>
</body>
</html>