JSON与angular和PHP结合使用 [英] JSON get with angular and PHP

查看:100
本文介绍了JSON与angular和PHP结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问你一点帮助.当我离开服务时,尝试在控制台上与前端的一部分(php)进行有角度的通信时,我得到一个空数组

I wanted to ask you a little help . When I try to communicate my front end in angular with the part of the back end ( php ) on the console as soon as I left the service I get an empty array

控制器:

angular.module('pageModule')
.controller('pageController', ['$scope', 'homeService', 'pageService', function($scope, homeService, pageService){

  $scope.pages = new Array();

  pageService.getPage().then(function(response){
    var elenco = response.data;
    console.log(elenco);
    for(var i = 0; i < elenco.length; i++)
      $scope.pages.push(elenco[i]);
  });
  console.log($scope.pages);
}]);

这是服务:

angular.module('pageModule')
.service('pageService', function($http){
  function getPage(){
    return $http.get('../angCMS/server/php/page.php');
  }
  return{
    getPage: getPage
  };
});

这是PHP部分:

<?php
require_once 'core/class.core.php';
$page = new angCMS(); //this function connected the DB
if($_SERVER['REQUEST_METHOD'] == 'GET'){
  header('Content-type: application/json');
  echo json_encode($page->getPage());
}

 ?>

在控制台中:

pageModuleController.js:12 []
pageModuleController.js:8 Object {id: "1", title: "prova", content: "prova"}


推荐答案

您的代码没有错. $ http.get始终异步执行.这样,您就可以在服务的最后一行上找到一个空数组.在$ http检索php页面响应之后,将在.then(...)中调用您的函数并填充$ scope.pages

Is nothing wrong with your code. $http.get is always executed async. This is way you have an empty array on last line in the service. After $http retrieves the php page response, will call your function in .then(...) and feds $scope.pages

这篇关于JSON与angular和PHP结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆