Requirements:
php reads the two-dimensional array from the database and passes it to js
Implementation steps:
php:json_encode → json → js:eval
That is, use json_encode() in php to convert the php two-dimensional array into json format, pass it to js, and use eval() to parse to get the js two-dimensional array.
Code:
php:
<?php header("Content-Type: text/html; charset=utf8") ; $con=mysqli_connect("url","name","password","databasename"); // Check connection if (mysqli_connect_errno($con)) echo "Failed to connect to MySQL: " . mysqli_connect_error(); mysqli_query($con,"set character set 'utf8'"); mysqli_query($con,"set names 'utf8'"); $json_arr = array(array("a","b","c",1,2,3),array("q","w",1,2)); $jsonstr = json_encode($json_arr); ?> var json=<?=$jsonstr?>;
<script type="text/javascript" src="http://.../test.php"></script> <script language="javascript" type="text/javascript"> $(document).ready(function(){ var jsonstr =eval(json); for(var k=0;k<jsonstr.length;k++){ for(var i=0;i<jsonstr[k].length;i++) alert(jsonstr[k][i]); } }) </script>
Problems encountered:
1. When the two-dimensional array in php is converted into json using json_encode(), the second-dimensional array can be echoed out, but the converted json is empty.
Check the information online to determine that the problem is that the second-dimensional array contains non-utf8 encoding. Sure enough, I swapped the positions of the second-dimensional array in the two-dimensional array, and the json of the first array became empty.
Conclusion: json_encode() can convert multi-dimensional arrays, but the basic requirement is to encode it into utf8. When a sub-array in a multi-dimensional array is converted from json to null, it is very likely that this sub-array contains elements whose encoding is not utf8.
2.wamp mysql In phpmyadmin, I see that the content of the data table is normal Chinese characters, but when I read it and print it with php, I found that the Chinese characters have changed? .
The organization method of each table in the database is utf8_general_ci, which is also declared in the php file
header("Content-Type: text/html; charset=utf-8") ; ... mysqli_query($con,"set character set 'utf-8'"); mysqli_query($con,"set names 'utf-8'");
It should be like this:
header("Content-Type: text/html; charset=utf8") ; ... mysqli_query($con,"set character set 'utf8'"); mysqli_query($con,"set names 'utf8'");