无法从服务器上的PHP文件获取数据作为JSON

时间:2017-06-19 11:43:50

标签: javascript php json phpmyadmin xmlhttprequest

我在服务器上有一个数据库,其中包含一个表customers和一列names。我想向服务器发出请求,请求customers表中的前2条记录。一旦我运行程序,浏览器就无法显示记录,它显示未定义。看下面的图片。

enter image description here

.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>

1 个答案:

答案 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>