【问题标题】:Getting data as JSON from a PHP file on the server从服务器上的 PHP 文件中获取 JSON 格式的数据
【发布时间】:2017-06-17 22:27:53
【问题描述】:

我正在使用AJAX 调用从服务器请求PHP 文件。 PHP 文件包含一些对象。 JSON.parse() 用于将结果转换为 JavaScript 对象。所以问题是运行程序后我在浏览器控制台中看到以下错误:

Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange (index.php:15)

虽然我的 Apache 服务器和 PHP 运行良好,但我不知道程序为什么不工作。 我正在开发的程序:

index.php:

    <p id="demo"></p>

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();

</script>

demo_file.php:

    <?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

【问题讨论】:

    标签: javascript php json ajax xmlhttprequest


    【解决方案1】:

    你可以用json_encode()函数在php中构建json:

    <?php
    
    $myObj = new stdClass(); 
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->city = "New York";
    
    echo json_encode($myObj);
    

    【讨论】:

    • Mohammad Hamedani,感谢您的回答。我已经知道了。但我想发出 XMLHTTP 请求以从文件中获取数据。在这种情况下,PHP 文件位于服务器中,而 Javascript 是一个客户端程序——这正是我在我的程序中尝试做的事情,但它不起作用。你能帮我解决这个问题吗?
    • 你发现问题了吗?
    【解决方案2】:

    也许你有 $myObj 未初始化的警告:

    <?php
    header('Content-type: text/json');
    $myObj = new stdClass; 
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->city = "New York";
    echo json_encode($myObj);
    

    【讨论】:

    • 非常感谢。我想拥抱你!
    【解决方案3】:

    虽然这个问题是 1 年前提出的,但如果我是对的,仍然没有正确回答。我遇到了同样的问题,并通过提供正确的文件路径来解决它。

    解决方案:如果你的客户端代码和服务器代码在同一个文件夹中,逻辑上不需要给出根文件夹的路径,但在这种情况下你需要提供根文件夹。例如:如果您的 client.php 和 demo_file.php 文件在同一个文件夹中 Pages 那么解决方案是:

    <p id="demo"></p>
    
    <script>
    
    var xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.name;
        }
    };
    xmlhttp.open("GET", "Pages/demo_file.php", true);
    xmlhttp.send();
    

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2011-12-23
      • 2011-09-18
      • 2017-11-20
      相关资源
      最近更新 更多