2017-08-09 117 views
0

我有个问题与输出从MySQLAngularJS NG-重复未示出数据表

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; 

CONTROLER代码:

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

感谢您的帮助常数。

+0

的“\”是正确的。当你捕获数组时,javascript显示错误? –

+0

检查此答案以澄清反斜杠。 https://stackoverflow.com/a/10314758/8303694 –

回答

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); 
+0

非常感谢你:) 并有另一个问题.... 我如何在MySQL中使用非标准符号(ščžážý)?...与这些符号也不起作用。 –

+1

这可能是另一个问题的主题。我认为你需要为你的数据库设置一个UTF-8排序规则,并将你的连接从PHP脚本应用到数据库。类似的问题:https://stackoverflow.com/questions/9968438/mysql-utf8-collat​​ion-data-with-accents-not-displayed-properly-when-php-fetched – Fotis

1

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

还有一个在你的代码复制json_encode,你while循环中,所以你在做重复的JSON编码,因此意外输出