【问题标题】:AngularJS ng-repeat not showing data in tableAngularJS ng-repeat 未在表中显示数据
【发布时间】:2018-01-17 23:53:41
【问题描述】:

我的 MySQL 输出有问题

getCustomers.php

$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"}]

所以,如果我在 data 中写入常量,它工作得非常好

$scope.list = [{"ancestry":"1286794218","trusted":"126"}];

感谢您的帮助。

【问题讨论】:

标签: php mysql angularjs


【解决方案1】:

您正在对您的回复进行双重编码。反斜杠之所以存在,是因为 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);

【讨论】:

  • 非常感谢 :) 还有另一个问题......我如何在 MySQL 中使用非标准符号(ščžážý)?......虽然这些符号也不起作用。
  • 这可能是一个单独问题的主题。我认为您需要为您的数据库设置一个 UTF-8 排序规则,并将其应用于从 PHP 脚本到数据库的连接。类似问题:stackoverflow.com/questions/9968438/…
【解决方案2】:

我认为您需要在 php 代码中使用header('Content-Type: application/json');,以便服务器以 JSON 内容类型响应。

在您的代码中还有一个重复的json_encode,在您的while 循环内,所以您正在执行重复的 json 编码,因此出现了意外的输出

【讨论】:

    【解决方案3】:

    在您的响应中使用 JSON.parse()。 JSON.parse docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 2017-07-13
      • 2020-08-16
      • 2018-06-28
      • 2016-09-06
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多