我正在尝试将我的angularjs应用程序连接到一个简单的php脚本,它只是从sqlite3数据库返回一个sql查询。
这是我的PHP脚本:
<?php
date_default_timezone_set('UTC');
try {
$objDb = new PDO('sqlite:../dbase/shopper');
$objDb -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT item.* ,
t.name AS type_name
FROM items item
INNER JOIN types t
ON t.id = item.type
ORDER BY item.date ASC";
$result = $objDb->query($sql);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$items = $result->fetchAll();
$sql = "SELECT *
FROM types
ORDER BY id";
$result = $objDb->query($sql);
echo var_dump($result);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$types = $result->fetchAll();
echo json_encode(array(
'error' => false,
'items' => $items,
'types' => $types
), JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
} catch (PDOException $e) {
echo json_encode(array(
'error' => true,
'message' => $e->getMessage()
),JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
}
当我检查php文件地址时,我可以得到结果:
object(PDOStatement)#3 (1) { ["queryString"]=> string(41) " SELECT * FROM types ORDER BY id " }
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
如果我使用angularjs,我会得到未定义的结果。
.controller('ShoppingListController', function($scope, $http, $log ){
$scope.types = [];
$scope.items = [];
$scope.item = '';
$scope.qty = '';
$scope.types = '';
$scope.select = function( ) {
$http({method: 'GET',url: 'mod/select.php'})
.success(function(data){
console.log(data)
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
})
.error(function(data,status,header){
throw new Error('Something went wrong with selecting record');
});
};
$scope.select();
});
console.log(数据)显示:
object(PDOStatement)#3 (1) {
["queryString"]=>
string(41) " SELECT *
FROM types
ORDER BY id "
}
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
我该如何解决这个问题?
答案 0 :(得分:4)
您必须返回JSON响应。从数据库中获取关联数组并返回:
echo json_encode($db_query);
在Angular中,您可以将范围设置为等于响应ex:
$scope.items = data.items;
然后,您可以在视图中访问此内容(请确保ng-controller="ShoppingListController"
)。
迭代数据:
ng-repeat="item in items"
然后,您可以通过item.id
或阵列中的任何密钥访问每个部分。
此外,无需在顶部设置$scope.items
。
编辑:
.controller('ShoppingListController', function($scope, $http, $log) {
function select() {
$http.get('mod/select.php')
.success(function(data) {
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
});
}
select();
});
答案 1 :(得分:0)
删除var_dump();
并且您不需要与var_dump()
回应,它已经附加到输出缓冲区。 var_dump()
使您的回复无效JSON。