简体   繁体   中英

AngularJs, Ionic: $http.get does not work

I am trying to load data from a mysql database with a php file and then load the result in my angularjs file. However, it is not working. I tried it with the $http service using the .get() function.

config.php:

<?php
define('HOST','localhost');
define('NAME','test');
define('USER','root');
define('PW','');

$mysqli = new mysqli(HOST,USER,PW,NAME);
if(mysqli_connect_errno())
{
 //echo("Failed to connect, the error message is: ".mysqli_connect_error());
 exit();
}
else
{
 //echo "Connection success";
}
?>

loadDatabase.php:

  <?php
require_once'config.php';

$query = "select * from lebensmittel";
$result = $mysqli->query($query);

if(mysqli_num_rows($result) > 0)
{
    echo " Tupels vorhanden";
    while ($row = $result->fetch_assoc()) 
    {
        $data[] = $row;
    }
}

header('Content-Type: application/json');
echo json_encode($data);
?>

controller.js:

angular.module('starter.controllers', [])
.controller('AppCtrl', function ($scope, $ionicModal, $timeout, $http) {

   $scope.items = [];

   function loadData()
   {
       $http.get("http://localhost/4n/db_zugriff/loadDatabase.php").success(function (data) {
           $scope.items = data;
       }).error(function () {
           console.log("Error: can't load from php");
       });
   }

   loadData();

/*
$scope.items = [
   { id: 1, name: 'milk', date: '01-01-2016', amount: 1000 },
   { id: 2, name: 'cheese', date: '01-01-2016', amount: 250 },

];
   */

});

output.html:

<ion-view view-title="Output">
    <ion-content data-ng-app="starter" ng-controller="AppCtrl">

        <ion-list >
            <ion-item ng-repeat="item in items">
                {{item.name}} {{item.date}}
            </ion-item>
        </ion-list>

    </ion-content>
</ion-view>

How can I fix this? I appreciate your help!

Your ng-app is wrong, it should be

  <ion-content data-ng-app="starter.controllers" ng-controller="AppCtrl">

Also have a function declared like this and call it in ng-init ,

$scope.loadData = function()
{
 $http.get("http://localhost/4n/db_zugriff/loadDatabase.php").success(function                                                     (data) {
           $scope.items = data;
       }).error(function () {
           console.log("Error: can't load from php");
       });
    });
}

HTML:

  <ion-view view-title="Output">
        <ion-content data-ng-app="starter.controllers" ng-controller="AppCtrl">
            <ion-list ng-init="loadData()">
                <ion-item ng-repeat="item in items">
                    {{item.name}} {{item.date}}
                </ion-item>
            </ion-list>
        </ion-content>
    </ion-view>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM