我对MySQL的输出有问题
getCustomers.phpis
$query="select distinct c.ancestry, c.trusted from members c order by c.id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = json_encode($row);
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
和控制器代码:
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 100; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
问题是我从MySQL获得这种格式(例如(:
["{"ancestry":"12865794218","trusted":"128"}"]
但可以期待的是:
[{"ancestry":"1286794218","trusted":"126"}]
所以,如果我在数据中写入常量,它工作得很好
$scope.list = [{"ancestry":"1286794218","trusted":"126"}];
感谢您的任何帮助。
您正在对响应进行双重编码。反斜杠之所以存在,是因为json_encode
的第二个应用程序转义了第一个应用程序输出中的双引号。从 while 循环中取出json_encode
。
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row; // don't encode here
}
}
然后只需对其进行一次编码(就像您已经一样(。
$json_response = json_encode($arr);
我认为您需要在php代码中使用header('Content-Type: application/json');
,以便服务器使用JSON内容类型进行响应。
在while
循环中,代码中还有一个重复的json_encode
,因此您正在执行重复的json编码,因此会出现意外的输出
在响应中使用 JSON.parse((。JSON.parse 文档