在理解如何混合 AngularJS 和 PHP 时遇到一些困难。我最初只是尝试让 AngularJS 工厂调用 PHP 文件(获取查询),然后将其推回到我的 AngularJS 工厂, Controller 可以在其中使用数据。
这是我到目前为止所得到的,当我尝试console.log
结果时,这给了我“未定义”。
工厂
app.factory("PlantServiceLIVE", function($http) {
var mData = {};
$http.get('pages/getplants.php').success(function(data) {
mData.data = data;
});
return mData;
});
Controller
app.controller('TestController', function($scope, $http, PlantServiceLIVE) {
$scope.Plants = PlantServiceLIVE.mData;
console.log(JSON.parse($scope.Plants));
});
PHP(刚刚验证以下内容也有效)
$sql = "SELECT * FROM PlantTable";
$result = $conn->query($sql);
echo json_encode($result);
第一次这样做,不知道我到底做错了什么。
我得到的唯一开发者控制台错误是SyntaxError: Unexpected token u
,从我读到的内容来看,这仅意味着数据未定义
。
最佳答案
问题不在于 Angular ,而在于 Ajax 请求如何工作。
AJAX 请求异步工作,这意味着响应不会立即可用。您需要做的是准备代码,以便在响应准备好时收到通知。 在普通的 javascript 中,您可以使用回调来获取通知, Angular 使用 promises
要使其正常工作,您需要稍微更改代码。 工厂
app.factory("PlantServiceLIVE", function($http) {
var mData = {
gettingPlants: function(){
return $http.get('pages/getplants.php')
}
};
return mData;
});
Controller
app.controller('TestController', function($scope, $http, PlantServiceLIVE) {
PlantServiceLIVE.gettingPlants.then(function(response){
console.log(JSON.parse(response.data));
});
});
关于javascript - AngularJS Factory 调用 PHP,然后返回 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858566/