首页 > 解决方案 > angular http get 从 php 文件返回空的 json 数据

问题描述

我想设置一个带有角度的页面(版本 1.6.10),它显示来自 php 文件(example_file.php)的数据,该文件使用 json_encode 从 mysql 数据库表创建一个 json 页面。直接在浏览器中访问 php 文件会正确显示 json 数据,但是当我在角度中使用 $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>

标签: phpangularjsjson

解决方案


推荐阅读