Putting mySQL Database Information into a JavaScript Array
我尝试使用上面将 MYSQL 数据传递到 AJAX 的示例,但它只使用一维数组,如何从多维数组中获取数据?
这是我尝试过的一些测试代码(load_ajax.php):
<?php
$mysqli=mysqli_connect("localhost","root","admin","database_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$mysqli->set_charset("utf8");
$i=0;
$arraylist=""; // Initialise local array for icons
$result = $mysqli->query('select * from word_table');
while($row=$result ->fetch_object()) {
$arraylist[$i]["word_id"]=$row->word_id;
$arraylist[$i]["word_name"]=$row->word_name;
$i++;
}
//convert the PHP array into JSON format, so it works with javascript
echo json_encode($arraylist);
?>
在 HTML 中 (load_ajax.html):
$.ajax({
url: "load_ajax.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]["word_id"]+"/"+data[i]["word_name"]);
}
}
});
上面的代码对我来说不起作用。以前我只使用 PHP 生成数组并直接打印为 HTML。现在我想使用 AJAX 将 MySQL 数据从 PHP 加载到 JavaScript 多维数组中,这样可以与其他本地函数进行更多交互。
最佳答案
我在不同的浏览器(Firefox)上尝试了该代码,它工作没有问题。
我不知道为什么它在 Chrome 中不起作用。重新加载页面不会让它再次工作。不得不关闭窗口并重试。
正在运行,抱歉!
关于mysql - 通过ajax从mysql/php获取多维结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41541612/