我试图建立一个网站,可以使用jquery显示mysql数据库中的某些数据,但我无法弄清楚如何用数据填充表。
我的PHP文件如下所示:
<?php
$servername = "localhost";
$database = "testdatabase";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$getinfo = "SELECT * FROM greenhouse";
$names = $conn->query($getinfo);
$str = array();
if ($names->num_rows > 0) {
// output data of each row
while($res = $names->fetch_array(MYSQL_ASSOC)) {
$str[] = $res;
}
}
echo json_encode($str);
?>
这是我的脚本:
<script>
function get_greenhouses(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//var returnval = JSON.parse(xmlhttp.responseText);
//document.getElementById("main_text").innerHTML = dataSet[0];
start_table(JSON.parse(xmlhttp.responseText));
//document.getElementById("main_text").innerHTML = returnval[0].Name;
}
}
xmlhttp.open("GET","get_greenhouses.php", true);
xmlhttp.send();
}
function start_table(greenhousedata){
console.log(greenhousedata);
//document.getElementById("main_text").innerHTML = greenhousedata[0].Adress;
$('#example1').DataTable( {
"ajax": greenhousedata,
columns: [
{ title: "Name" },
{ title: "ID" },
{ title: "plant type" },
{ title: "install date" },
{ title: "adress" }
]
} );
}
$(function () {
get_greenhouses();
});
</script>
所以我试图有一个功能get_greenhouses()在文档加载时启动。在其中,我向PHP文件发出请求,以获取数据,将其编码为json,然后将其发送回去。当我获取数据时,我想将其传递给start_table()函数,然后使用它来填充表。现在,我收到一条错误消息:
DataTables警告:表格ID = example1-无效的JSON响应。有关此错误的更多信息,请参见http://datatables.net/tn/1
但是,当我点击链接并检查从php文件中获取的数据时,它显示为json,据我所知,它看起来是正确的。
有人可以告诉我我在做什么错吗,或者是否有更好的方法呢?
最佳答案
请使用下面显示的代码。
只需输入正确的greenhouse
表字段名,而不是data
选项指定的伪字段名即可。
function get_greenhouses(){
$('#example1').DataTable( {
ajax: {
url: "get_greenhouses.php",
dataSrc: ""
},
columns: [
{ data: "name", title: "Name" },
{ data: "id", title: "ID" },
{ data: "plant", title: "Plant type" },
{ data: "dt_install", title: "Install date" },
{ data: "address", title: "Address" }
]
});
}
关于php - 结合使用DataTable和json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369658/