AngularJS通过php文件从MySQL获取数据

时间:2015-11-07 16:55:08

标签: php mysql angularjs http

这是我的问题:

我做了一个非常基本的angularJS应用程序,它应该从php文件中获取数据并将它们绑定到范围内。所以php文件(链接到MySQL DB)的输出是:

[{"hum":"55.36","temp":"20.86","unixtime":"2015-10-29 17:39:42","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"},
{"hum":"55.33","temp":"20.84","unixtime":"2015-10-29 17:39:50","coreid":"xxxxxx","moist":"0.00","volt":"4.30","soc":"114"},
{"hum":"55.42","temp":"20.84","unixtime":"2015-10-29 17:39:58","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"}]

该应用的代码是:

var dashb = angular.module('dashboard', []);

//avoid cross domain issue
dashb.config(['$httpProvider', function($httpProvider) {
$http.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);


dashb.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
         $http.get("http://www.domain.com/php_file_url.php")
            .success(function(data) {
                $scope.data = data;
                $scope.hum = data.hum;

            })
            .error(function() {
                $scope.data = "error in fetching data";

            });


    }]);

但是当我运行它时它不起作用。我没有数据。我做错了什么?谢谢

1 个答案:

答案 0 :(得分:0)

如果您确定要从查询中获取数据,则只需将其作为JSON发送即可。在echo $res;行之前添加此内容:

header('Content-Type: application/json');

此外,在您的代码中,更改以下内容

$http.defaults.useXDomain = true;

$httpProvider.defaults.useXDomain = true;