2015-02-09 102 views
0

我正在創建一個單一功能:使用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

回答

0

這裏有兩個小錯誤。

你不能指定某個函數的返回值。看看你在這條線上做什麼:$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