我正在尝试使用php文件从mysql数据库加载数据,然后将结果加载到我的angularjs文件中。但是,它不起作用。我使用.get()函数使用$ http服务尝试了它。
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>
我该如何解决这个问题? 感谢您的帮助!
答案 0 :(得分:0)
您的ng-app错误,应该是
<ion-content data-ng-app="starter.controllers" ng-controller="AppCtrl">
还有一个像这样声明的函数,并在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>