Javascript 无法从angularJS中的mysql提取数据
我在angularJS很新。我已经向mysql的所有客户展示了使用。因此,我在cotroller和service中写道:Javascript 无法从angularJS中的mysql提取数据,javascript,ajax,json,angularjs,Javascript,Ajax,Json,Angularjs,我在angularJS很新。我已经向mysql的所有客户展示了使用。因此,我在cotroller和service中写道: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function init() { $scope.customers = customersService.getCustomers(); } }); app.service('c
app.controller('CustomersController', function ($scope, customersService, $http) {
init();
function init() {
$scope.customers = customersService.getCustomers();
}
});
app.service('customersService', function ($http) {
this.getCustomers = function () {
return customers;
};
// my issue is here
$http.get("app/server/read.php")
.success(function(data){
var customers = data;
});
});
我用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);
php将json数组返回为:
[{"id":"36","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"37","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"38","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"39","firstName":"","lastName":"","address":"","city":""},{"id":"40","firstName":"asd","lastName":"asd","address":"","city":"asd"}]
我不明白如何将这个json对象数组放入变量customers
,因为当我直接将这个数组写入变量customers
时,它就工作了。i、 e
var customers = [{"id":"36","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"37","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"38","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"39","firstName":"","lastName":"","address":"","city":""},{"id":"40","firstName":"asd","lastName":"asd","address":"","city":"asd"}]
但是我不能动态地将它放在get方法result成功之后。从您的服务返回
$http
承诺,然后在.success回调中设置$scope属性
app.controller('CustomersController', function ($scope, customersService, $http) {
init();
function init() {
customersService.getCustomers().success(function(data){
$scope.customers = data;
});
}
});
app.service('customersService', function ($http) {
this.getCustomers = function () {
return $http.get("app/server/read.php");
};
});
如果我这样使用
$http.get(“app/server/read.php”).success(函数(数据){var customers=data;});})代码>,我发现有一个错误就是,客户没有定义。请告诉我如何定义客户,因为如果我按照你的方式,其他操作会受到影响。var客户定义客户,但你不想使用var,你想像我在回答中所做的那样将其添加到范围中。是的,我理解,但是,是否可以从mysql中提取数据并将其放入变量中,然后将其添加到范围中?是的var something=data$scope.customers=something代码>