角度http获取从PHP文件返回空的JSON数据

时间:2018-07-24 14:42:40

标签: php angularjs json

我想建立一个带有角度的页面(1.6.10版),该页面显示php文件(example_file.php)中的数据,该文件使用json_encode从mysql数据库表中创建一个json页面。直接在浏览器中访问php文件可以正确显示json数据,但是当我在angular中使用$ http进行访问时,它什么也不会返回。如果我将生成的json文件另存为json文件(example_file.json)并使用它,那么它可以正常工作吗?

example_file.php

<?php
 header("Access-Control-Allow-Origin: *");
 header("Content-Type: application/json");

 include('../../includes/Db.php');
 include('../../includes/item.php');
 $someItems = new Item();
 $items = $someItems->getItems();
 $data = array();
 foreach($items as $item){
   $data[] = array("id" => htmlspecialchars($item->id),
                  "image"  => htmlspecialchars($item->name),
                  "url"    => htmlspecialchars($item->url),
                  "alt"    => htmlspecialchars($item->alt_desc),
                  "title"  => htmlspecialchars($item->title),
                  "active" => htmlspecialchars($item->active),
                  "order"  => htmlspecialchars($item->order_by));
 }

 $json = json_encode($data);
 echo $json;
?>

这将返回

[{"id":"18","image":"catalogue.jpg","url":"/catalogue","alt":"New catalogue out now!","title":"New catalogue","active":"1","order":"1"},{"id":"4","image":"item1.jpg","url":"\/item1\/","alt":"item1 alt description","title":"item1 description","active":"1","order":"2"},{"id":"7","image":"item2.jpg","url":"\/item2\/","alt":"","title":"item2 title","active":"1","order":"3"},{"id":"5","image":"item3","url":"\/item3\/","alt":"","title":"Item3 description","active":"1","order":"4"},{"id":"1","image":"item4.jpg","url":"","alt":"Item4 alt description","title":"item4 title","active":"1","order":"6"}]

角度模块moc.js

(function () {

var moc = function($http) {
    var getItems = function () {
        return $http.get("data/example_file.php")
        .then(function(response) {
           return response.data;
        })
    };
    return {
       getItems: getItems,
    };
};
var module = angular.module("mocApp");
module.factory("moc", moc);

}());

角度控制器myCtrl.js

(function () {
 var app = angular.module("mocApp");
 var homeCtrl = function($scope, moc) {
    var onComplete = function(data) {
        $scope.items = data;
    };
    var onError = function (reason) {
        $scope.error = "Could not fetch data";
    };
    moc.getItems().then(onComplete, onError);
 };
 app.controller("myCtrl", myCtrl);
}());

html文件item.html

<div>
{{error}}
</div>

<table>
<thead>
  <tr>
    <th>Name</th>
    <th>url</th>
    <th>Order</th>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="item in items">
    <td>
        {{item.name}}
    </td>
    <td>{{item.url}}</td>
    <td>{{item.order_by}}</td>
  </tr>
</tbody>
</table>

0 个答案:

没有答案