如何将json对象数组从mysql推入angularjs中的空数组

时间:2014-03-30 08:55:47

标签: json angularjs

我一直在尝试从mysql中检索数据。所以,我用PHP编写:

$result = mysqli_query($con,"SELECT * FROM customers");
$return_arr = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rowArr = array(
    'id' => $row['id'],
    'firstName' => $row['firstname'],
    'lastName' => $row['lastname'],
    'address' => $row['address'],
    'city' => $row['city']
);
$return_arr[] = $rowArr;
}
echo json_encode($return_arr);

我想将这些数据推送到angularjs成功数组中:

var customers = [];

$http.get("app/server/read.php")
    .success(function(data){
        customers.push(data);
        //console.log(data);
    });

如果我从mysql发送单行,它会收到,即当我在php echo json_encode($rowArr);中写入时,然后var customers能够接收,否则不能用于多行。在控制台中我得到:

[Object { id="36", firstName="asdasd", lastName="asdasd", more...}, Object { id="37", firstName="asdasd", lastName="asdasd", more...}, Object { id="38", firstName="asdasd", lastName="asdasd", more...}, Object { id="40", firstName="asd", lastName="asd", more...}, Object { id="41", firstName="asdasd", lastName="asdasd", more...}, Object { id="42", firstName="asdasd", lastName="asdas", more...}, Object { id="43", firstName="asdasd", lastName="asdasd", more...}]

如果我做错了,你能帮助我吗?

更新

HTML:

<div class="col-lg-3 card" data-ng-repeat="customer in customers | orderBy:'lastName'">
    <button class="btn close cardClose" data-ng-click="deleteCustomer(customer.id)">&times;</button>
    <div class="cardHeader">{{customer.firstName + ' ' + customer.lastName}}</div>
    <div class="cardBody">{{customer.city}}</div>
</div>

控制器:

app.controller('CustomersController', function ($scope, customersService, $http) {
init();

function init() {
    $scope.customers = customersService.getCustomers();
 }
});

服务:

app.service('customersService', function ($http) {
    this.getCustomers = function () {
    return customers;
};

var customers = [];
$http.get("app/server/read.php")
    .success(function(data){
        //customers.push(data);
        customers = data;
    });
});

1 个答案:

答案 0 :(得分:2)

试试这个:

app.service('customersService', function ($http, $q) {
   var deferred = $q.defer();
   $http.get('app/server/read.php').then(function(res) {
     deferred.resolve(res);
   });

   var getCustomers = function() {
     return deferred.promise;   
   };

   return {
     getCustomers: getCustomers
   };
});

在你的控制器中:

 customersService.getCustomers().then(function(customers) {
    $scope.customers = customers;
 });
相关问题