weixin_33696106 2015-02-09 09:58 采纳率: 0%
浏览 10

AngularJS Ajax调用

I am creating a single functionality : On a click of a button using AngularJS, i make an ajax call to some JSON data from the server.

Without the button functionality the following code is working:

<!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>

But when i add a button click functionality the data doesnt get displayed on click of that button

<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>

Please Help!

</div>
  • 写回答

1条回答 默认 最新

  • lrony* 2015-02-09 10:11
    关注

    You've got two little errors here.

    You can't assign something to the return value of a function. Look at what you're doing on this line: $scope.getData()= $http....... This is telling JS to run $scope.getData as a function, but you can't use an equal sign right afterwards to assign something to that return value. $scope.getData is also likely undefined, which is just going to be a script error.

    The second thing you're doing wrong is that the code you wrote, assuming you fixed #1 and made it $scope.getData = $http.... instead, is that you're immediately running that $http.get code, and then assigning the return to $scope.getData. What you really want to do is create a reusable function. You do this as follows:

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

    Fix those two problems, and you should be golden.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效