我在服务器上有一个数据库,其中包含一个表customers
和一列names
。我想向服务器发出请求,请求customers
表中的前2条记录。一旦我运行程序,浏览器就无法显示记录,它显示未定义。看下面的图片。
.PHP:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("127.0.0.1", "abc", "def", "mydatabase");
$result = $conn->query("SELECT names FROM " . $obj->table . " LIMIT " . $obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
html的:
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":2 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>
答案 0 :(得分:1)
您必须在js循环中使用names
而不是name
对象,因为在您的选择查询中,您有names
列且结果具有names
属性。
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":2 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
console.log(myObj)
for (x in myObj) {
txt += myObj[x].names + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>