简体   繁体   English

来自PHP的$ http.get JSON无法正常工作

[英]$http.get JSON from PHP not working

First of all I am new in programming and I am not a native English speaker, so please forgive me any mistakes in correct naming things etc. in the following question :) 首先,我是编程新手,我不是母语为英语的人,所以请原谅我在下面的问题中正确命名等方面的任何错误:)

This is my JSON output: 这是我的JSON输出:

[{"Year":"2017","Month":"1","Day":"1"},{"Year":"2017","Month":"1","Day":"2"},{"Year":"2017","Month":"1","Day":"3"},{"Year":"2017","Month":"1","Day":"4"},{"Year":"2017","Month":"1","Day":"5"},{"Year":"2017","Month":"1","Day":"6"},{"Year":"2017","Month":"1","Day":"7"},{"Year":"2017","Month":"1","Day":"8"},{"Year":"2017","Month":"1","Day":"9"},{"Year":"2017","Month":"1","Day":"10"},{"Year":"2017","Month":"1","Day":"11"},{"Year":"2017","Month":"1","Day":"12"},{"Year":"2017","Month":"1","Day":"13"},{"Year":"2017","Month":"1","Day":"14"},{"Year":"2017","Month":"1","Day":"15"},{"Year":"2017","Month":"1","Day":"16"},{"Year":"2017","Month":"1","Day":"17"},{"Year":"2017","Month":"1","Day":"18"},{"Year":"2017","Month":"1","Day":"19"},{"Year":"2017","Month":"1","Day":"20"},{"Year":"2017","Month":"1","Day":"21"},{"Year":"2017","Month":"1","Day":"22"},{"Year":"2017","Month":"1","Day":"23"},{"Year":"2017","Month":"1","Day":"24"},{"Year":"2017","Month":"1","Day":"25"},{"Year":"2017","Month":"1","Day":"26"},{"Year":"2017","Month":"1","Day":"27"},{"Year":"2017","Month":"1","Day":"28"},{"Year":"2017","Month":"1","Day":"29"},{"Year":"2017","Month":"1","Day":"30"},{"Year":"2017","Month":"1","Day":"31"}]

I have checked it on valiator and it was accepted. 我已经在valiator上检查了它并且被接受了。

This is a RESTful API, using SlimApp, Apache virtual host, mysql database. 这是一个RESTful API,使用SlimApp,Apache虚拟主机,mysql数据库。

This is a 这是一个

calendar.php , which gets the JSON content from the SQL table: calendar.php ,从SQL表中获取JSON内容:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App;

// Get All Customers
$app->get('/api/calendar', function (Request $request, Response $response) {

    // echo 'CALENDAR'; });

    $sql = "SELECT * FROM days";

    try {
    // Get DB Object
    $dbcalendar = new dbcalendar();
    //Connect
    $dbcalendar = $dbcalendar->connect();

    $stmt = $dbcalendar->query($sql);
    $dbcalendar = $stmt->fetchAll(PDO::FETCH_OBJ);
    // $dbcalendar = null;

    echo json_encode($dbcalendar);

    } catch(PDOException $e) {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }
});`. 

Here are the files from AngularJS: 以下是AngularJS的文件:

days.js days.js

app.factory('days', ['$http', function($http) {
    return $http.get('http://slimapp/api/calendar/index.html')
        .success(function(data) {
            return data;
        })
        .error(function(err) {
            return err;
        });
}]);`,

DaysController.js DaysController.js

app.controller('DaysController', ['$scope', 'days', function($scope, days) {
    days.success(function(data) {
        $scope.days = data;
    });
}]);,

app.js app.js

var app = angular.module('CalendarApp', ['ngRoute']);
app.config(function ($routeProvider) {
    $routeProvider
        .when("/", {
            controller: "DaysController",
            templateUrl: "views/test.html"
        })
        .otherwise({
            redirecTo: "/"
        });
});

test.html 的test.html

<div ng-repeat="day in days"> 
<p> {{day.Year}} </p>
</div>.

When I type in http://slimapp/api/calendar in the browser, the JSON content is displayed as shown above. 当我在浏览器中输入http:// slimapp / api / calendar时,将显示JSON内容,如上所示。

When put some other code into test.html , for example: <p> Hello world </p> , everything is displayed fine in the browser. 将一些其他代码放入test.html ,例如: <p> Hello world </p> ,一切都在浏览器中正常显示。

I use older version of AngularJS1.X, as this is the version I learned on CodeCademy. 我使用旧版本的AngularJS1.X,因为这是我在CodeCademy上学到的版本。 Therefore I use .success and .error inside my $http.get service. 因此我在$http.get服务中使用.success.error

I have also installed "Allow-Control-Allow-Origin *" extension in my Chrome browser. 我还在Chrome浏览器中安装了“Allow-Control-Allow-Origin *”扩展程序。

When I want to display the JSON content with test.html 当我想用test.html显示JSON内容时

<div ng-repeat="day in days"> 
    <p> {{day.Year}} </p>
</div>

I get the blank page in the browser. 我在浏览器中看到了空白页面。 There isn't any error message, nothing. 没有任何错误消息,没有。

Please help my, as I have been struggling with this issue for two days, reading lots of different explainations, comments and so. 请帮助我,因为我一直在努力解决这个问题两天,阅读许多不同的解释,评论等等。 I really got stuck :( 我真的卡住了:(

OK. 好。 I have changed calendar.php according to suggestion from the comment: 我根据评论的建议更改了calendar.php

`<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App;

// Get All Customers
$app->get('/api/calendar', function (Request $request, Response $response) {

    // echo 'CALENDAR'; });

    $sql = "SELECT * FROM days";

    try {
    // Get DB Object
    $dbcalendar = new dbcalendar();
    //Connect
    $dbcalendar = $dbcalendar->connect();

    $stmt = $dbcalendar->query($sql);
    $dbcalendar = $stmt->fetchAll(PDO::FETCH_OBJ);
    // $dbcalendar = null;

    echo json_encode($dbcalendar);
    header("Content-type:application/json");
    } catch(PDOException $e) {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }
});`

but the problem still exists. 但问题仍然存在。

Set the Content-Type to application/json when echoing JSON. 在回显JSON时将Content-Type设置为application/json This way JavaScript will automatically parse the response string as JSON, otherwise you will have to do so by converting the response by hand with JSON.parse() 这样JavaScript会自动将响应字符串解析为JSON,否则你必须通过JSON.parse()手动转换响应来实现。

Your PHP code is also error prone, if an exception is thrown that is not PDOException or does not inherit from it, then you will get no information about the error. 您的PHP代码也容易出错,如果抛出的异常不是PDOException或者不继承它,那么您将不会获得有关该错误的信息。

Have you tried returning the JSON response from SLIM ? 您是否尝试过从SLIM返回JSON响应 Barring that your db query is successful this should work: 除非您的数据库查询成功,否则这应该有效:

$app->get('/api/calendar', function (Request $request, Response $response) {

    // echo 'CALENDAR'; });

    $sql = "SELECT * FROM days";

    try {
        // Get DB Object
        $dbcalendar = new dbcalendar();
        //Connect
        $dbcalendar = $dbcalendar->connect();

        $stmt = $dbcalendar->query($sql);
        $dbcalendar = $stmt->fetchAll(PDO::FETCH_OBJ);
        // $dbcalendar = null;

        return $response->withJson($dbcalendar);
    } catch(PDOException $e) {
        $error = array('error' => array('text' => $e->getMessage()));
        return $response->withJson($error,500);
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM