Demand:
PHP read from the database to a two-dimensional array, passed to JS
Implementation steps:
Php:json_encode→json→js:eval
That is, using Json_encode () in PHP to convert a two-dimensional PHP array into JSON format, passed to JS, using eval() to parse the two-dimensional JS array.
Code:
Php:
<?php Header ("content-type:text/html; Charset=utf8 "); $con =mysqli_connect (" url "," Name "," Password "," DatabaseName ");//Check connectionif (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 ("A", "B", "C", "All-in-a-D"), Array ("Q", "W", Up)); $jsonstr = Json_encode ($json _arr);? >var json=<?= $jsonstr?>;
JS:
<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:
When a two-dimensional array in 1.php is converted to JSON using json_encode () , the second-dimensional array can echo out, but the JSON is converted to null.
Check the data online to determine the problem is that the second-dimensional array contains non-UTF8 encodings. Sure enough, I switched the second-dimensional array in the two-dimensional array to the first array with the JSON empty.
Conclusion:json_encode () can convert multidimensional arrays, but the basic requirements are encoded as UTF8. Encountering a sub-array conversion json in a multidimensional array is null, and it is very likely that this subarray contains elements that are not UTF8 encoded.
2.wamp MySQL in phpmyadmin see the data table content is normal Chinese characters, but in PHP read out print found that the Chinese characters have become? The
Each table in the database is organized in a utf8_general_ci,php file that also declares the
Header ("content-type:text/html; Charset=utf-8 ") Mysqli_query ($con," set character set ' Utf-8 ' "); Mysqli_query ($con," Set names ' Utf-8 ' ");
This code I have always been so used (before the use of the Wamp low version, or the use of the mysql_query, now that the error is discarded, changed to mysqli), has not appeared before the Chinese become? The situation. Online a check, the original is utf-8 and UTF8 this place ...
This should be the case:
Header ("content-type:text/html; Charset=utf8 ") Mysqli_query ($con," set character set ' UTF8 ' "); Mysqli_query ($con," Set names ' UTF8 ' ");
Conclusion: MySQL is the use of UTF8 bar ... No words.
PHP Two-dimensional array passed to JS problem solving record