【问题标题】:Cannot get data as JSON from a PHP file on the server无法从服务器上的 PHP 文件中获取 JSON 格式的数据
【发布时间】:2017-11-21 14:47:33
【问题描述】:

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

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

【问题讨论】:

  • 查看浏览器的开发者控制台,了解 Ajax 请求的响应详情。

标签: javascript php json phpmyadmin xmlhttprequest


【解决方案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>

【讨论】:

  • 哈梅谷,你这摇滚!简单的错误,我无法检测到。感谢它现在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多