Angular的$http与$location

但是对于一个web应用,angular是如何同服务端进行交互获得数据的呢?

<script type="text/javascript"> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope','$http',function($scope,$http){ $http({ method : 'GET', url : 'http/data.php', }).success(function(data,state,headers,config){ console.log(data,state,headers(),config); }).error(function(data){ console.log(data); }); }]); </script>

用过JQ的同学一看就知道了,我们重点看看success回调的参数。(别忘了我们需要controller上引入http的模块)

data:後端返回给我们的数据。

state:http状态码

headers:http头信息

config:ajax的配置信息 

我们还可以更简单的来使用get和post。

//get $http.get('http/data.php').success(function(data,state,headers,config){ console.log(data); }).error(function(data){ console.log(data); }); //post $http.post('http/data.php',{ name : 'xiecg', age : 18 }).success(function(data,state,headers,config){ console.log(data); }).error(function(data){ console.log(data); });

上面都很简单。

下面我们来看看如何用angular来实现跨域(百度搜索关键词补全)。

<div ng-controller="Aaa"> <input type="text" ng-model="name" ng-keyup="change(name)"> <input type="button" ng-click="change(name)" value="搜索"> <ul> <li ng-repeat="d in data">{{d}}</li> </ul> </div> <script type="text/javascript"> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope','$http','$timeout',function($scope,$http,$timeout){ var timer = null; $scope.data = []; $scope.change = function(name){ $timeout.cancel(timer); timer = $timeout(function(){ $http({ method : 'JSONP', url : 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+name+'&cb=JSON_CALLBACK', }).success(function(data,state,headers,config){ console.log(data); $scope.data = data.s; }).error(function(data){ console.log(data); }); },500); }; }]); </script>

我们分别添加了两个事件ng-keyup以及ng-click来传入用户需要搜索的关键词,为了考虑性能我们使用定时器延迟500毫秒执行change方法。

Angular的$http与$location

$location

<script type="text/javascript"> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope','$location',function($scope,$location){ var absUrl = $location.absUrl(); //URL地址 //$location.path('aaa').replace(); //禁止历史管理 var path = $location.path(); //文件路径,路由 //$location.hash('hello'); //设置哈希值 //$location.search({'age' : '19'}); //设置数据 var hash = $location.hash(); var url = $location.url(); //数据 var host = $location.host(); //主机名 var port = $location.port(); //端口号 var protocol = $location.protocol();//协议 console.log(protocol); }]); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwjfss.html