AngularJS $http服务(发送Ajax异步请求)


demo.html:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>AngularJS</title>  
    <script src="angular.min.js"></script>  <!-- 引入AngularJS框架 -->  
</head>  
<body ng-app="App">  
    <div ng-controller="DemoController">  
    </div>
    <script>  
          
        var App = angular.module('App',[]);  
  
        // $http服务(发送Ajax异步请求)  
        App.controller("DemoController",['$scope','$http',function($scope,$http) {  
            // $http 本质是对XMLHttpRequest对象的封装  
  
            // 发送Ajax异步请求  
            $http({  
                method: 'post',  
                url: './demo.html',  
                params: {name: '张三',age: 12},   // get请求时的参数 (和JQuery不同,JQuery都放在data中)  
                data: {name: '张三',age: 12},  // post请求时的参数  (AngularJS优先支持RESTFUL(不是SOAP接口)接口服务的方式(默认传JSON格式的数据));  
                //data: "name=张三&age=12",   // RESTFUL会在服务端处理JSON对象,AngularJS本身不处理JSON对象。(如果服务端接口不是RESTFUL接口,那么就不能直接传JSON数据)  
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}  
            }).success(function(data,status,headers,config) {  
                // ....  
            }).error(function(data,status,headers,config) {  
                // ....  
            });  
  
        }]);  
          
    </script>  
</body>  
</html>  



猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80150024
今日推荐