Angular的$http与$location

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Angular的$http与$location

小谢53   2020-05-15 我要评论

$http

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

<script type="text/javascript">
  var m1 = angular.module('myApp',[]);
  m1.controller('Aaa',['$scope','$http',function($scope,$http){
    $http({
      method : 'GET',
      url : 'httphttps://img.qb5200.com/download-x/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('httphttps://img.qb5200.com/download-x/data.php').success(function(data,state,headers,config){
  console.log(data);
}).error(function(data){
  console.log(data);
});

//post
$http.post('httphttps://img.qb5200.com/download-x/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方法。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们