Obtaining a JSON array from PHP via JavaScript in

2019-03-04 16:29发布

问题:

I am trying to to get a JSON array from a server side PHP file. I have the PHP set up to query a MySQL database and return the result as a JSON array. I'm using the ionic framework to develop an app. At the moment I have the app working with a hard coded JSON array, this is what needs to be replaced by the array gained from the PHP.

This is the file where the chats variable should contain the JSON array from the PHP file.

    angular.module('starter.services', [])


.factory('Chats', function() {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var chats = [{
    id: 0,
    name: 'Ben Sparrow',
    lastText: 'You on your way?',
    face: 'img/ben.png'
  }, {
    id: 1,
    name: 'Max Lynx',
    lastText: 'Hey, it\'s me',
    face: 'img/max.png'
  }, {
    id: 2,
    name: 'Adam Bradleyson',
    lastText: 'I should buy a boat',
    face: 'img/adam.jpg'
  }, {
    id: 3,
    name: 'Perry Governor',
    lastText: 'Look at my mukluks!',
    face: 'img/perry.png'
  }, {
    id: 4,
    name: 'Mike Harrington',
    lastText: 'This is wicked good ice cream.',
    face: '/img/mike.png'
  }];

  return {
    all: function() {
      return chats;
    },
    remove: function(chat) {
      chats.splice(chats.indexOf(chat), 1);
    },
    get: function(chatId) {
      for (var i = 0; i < chats.length; i++) {
        if (chats[i].id === parseInt(chatId)) {
          return chats[i];
        }
      }
      return null;
    }
  };
});

Here is where the array is accessed from within the application:

<ion-view view-title="Chats">
  <ion-content>
    <ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">

          <div class="list card">

<div class="item item-avatar">
    <img src="{{chat.face}}">
    <h2>{{chat.name}}</h2>
    <p>{{chat.lastText}}</p>
  </div>

  <div class="">
    <img ng-src="{{chat.face}}">
  </div>

  <a class="item item-icon-left assertive" href="#/tab/chats/{{chat.id}}">
    <i class="icon ion-cash"></i>
    Get Deal!
  </a>

</div>


      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

and below is the PHP file used:

<?php
define('HOST','host');
define('USER','user');
define('PASS','password');
define('DB','db');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sth = mysqli_query($con, "SELECT * FROM chats;");

$rows = array();

while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}

echo json_encode($rows);

mysqli_close($con);

?>

This is the controller.js:

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});

I've tried using an async call (which i'm not totally familiar with). I need the array to be ready at the start of the app

Thanks!

回答1:

This works :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('chats', function($http){
      var chats = [];

      var _loading = $http.get('http://swapi.co/api/people').then(function(res){
        console.log(res.data.results);
        chats = res.data.results;
      });

      return {
        loading: _loading,
        all: function(){
          return chats;
        }
      };
    });

    myApp.controller('ChatsCtrl', function($scope, chats){
      $scope.chats = [];
      chats.loading.then(function(){
        $scope.chats = chats.all();
      });

    });


  </script>
</head>
<body ng-app="myApp">
  <div ng-controller="ChatsCtrl">
    <ul>
      <li ng-repeat="chat in chats">{{chat.name}}</li>
    </ul>
  </div>
</body>
</html>


回答2:

Since the Ionic framework is built on Angular, you can use the $http service. You need to request that PHP file from the $http service and then you will be able to read it as JSON. Try something like this for starters:

Make a service that has your API set up already, then call it in your controller file.

angular.module('starter.services', [])
.factory('MYAPI', function() {
    return {
        getChats: function() {
            return $http.get('http://localhost/YOURFILEHERE.php');
        }
    }
});

Now, in your controller file, assuming you've injected the MYAPI service, you can call

MYAPI.getChats().then(function(response) {
    $scope.chats = response.data;
}, function(error) {
    console.error(error);
});

You will need to change the $http.get() path to reflect the path of the PHP file on your system.