AngularJS Ajax调用

问题描述:

我正在创建一个单一功能:使用AngularJS单击按钮时,我对来自服务器的一些JSON数据进行ajax调用。AngularJS Ajax调用

没有按钮功能下面的代码工作:

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
</head> 
 

 
<body> 
 

 
<div ng-app="" ng-controller="customersController"> 
 

 
<ul> 
 
    <li ng-repeat="x in names"> 
 
    {{ x.Name + ', ' + x.Country }} 
 
    </li> 
 
</ul> 
 

 
</div> 
 

 
<script> 
 
function customersController($scope,$http) { 
 
$http.get("http://www.w3schools.com//website/Customers_JSON.php") 
 
    .success(function(response) {$scope.names = response;}); 
 
} 
 
</script> 
 

 
</body> 
 
</html>

但是当我添加一个按钮,点击功能数据犯规得到显示该按钮的点击

<head> 
 
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
</head> 
 

 
<body> 
 

 
<div ng-app="" ng-controller="customersController"> 
 
    <button ng-click="getData()">Get Data</button> 
 

 
<ul> 
 
    <li ng-repeat="x in names"> 
 
    {{ x.Name + ', ' + x.Country }} 
 
    </li> 
 
</ul> 
 

 
</div> 
 

 
<script> 
 
    function customersController($scope, $http) { 
 
    $scope.getData()= $http.get("http://www.w3schools.com//website/Customers_JSON.php") 
 
     .success(function (response) { $scope.names = response; }); 
 
    } 
 
</script> 
 

 
</body> 
 
</html>

请帮忙!

+0

'$ scope.getData()= $ http.get(...)'。这不是有效的JavaScript代码。 – dfsq 2015-02-09 10:02:16

+0

感谢您的回复! 但是也尝试过您的代码,没有从点击按钮获取任何数据! – 2015-02-09 10:12:02

这里有两个小错误。

你不能指定某个函数的返回值。看看你在这条线上做什么:$scope.getData()= $http......。这是告诉JS 运行$scope.getData作为一个函数,但你不能使用等号后分配的东西,该返回值。 $scope.getData也可能是未定义的,这只是一个脚本错误。

你做错了的第二件事情是,你的代码写的,假设你固定的#1,并使其$scope.getData = $http....取而代之的,是你会立即运行$http.get代码,然后分配回$scope.getData。你真正想做的是创建一个可重用的函数。你这样做如下:

$scope.getData = function() { 
    // function instructions 
} 

解决这两个问题,你应该是金。

+1

Hurraayyy!非常感谢!有效!我是黄金:) – 2015-02-09 10:17:29