2017-08-09 53 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編碼,因此意外輸出