angularjs 中的ajax请求方式
$http介绍:
- 熟悉ajax技术的人应该都清楚使用方式,jquery中常用的请求方式也就三种
- $.ajax()方法--可以发送get和post请求、$.get()方法、$.post()方法
- $http中也是一样,只是语法稍有不同而已,对应的是$http()、$http.get()方法、$http.post()方法
$http的语法格式
1.$http请求方式模板
$http({
url:"", //地址
method:"", //请求方式
params:{ //get方式传递参数
a:1,
b:2
},
data:{ //post传递数据的方式
c:3,
d:4
}
}).then(function(res){
//正确的回调函数
console.log(res.data);
},function(){
//错误的回调函数(可省略不写)
})
-----------------------------------------------
2.$http.get()请求模板
$http.get('url',{ params:{a:1,b:2 }})
.then(function(){
//正确回调函数
},function(){
//错错回调函数
})
------------------------------------------------
3.$http.post()请求模板
$http.post('url',{a:1,b:2 })
.then(function(){
//正确回调函数
},function(){
//错错回调函数
})
以下是demo示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>angularjs demo</title>
</head>
<body ng-app="myApp" ng-controller="demoCtrl">
<ul>
<li ng-repeat="item in data">
{{item.name}} {{item.age}}
<!-- ng-bind-html可以解析html代码 -->
<div ng-bind-html="item.slogen"></div>
</li>
</ul>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-sanitize.min.js"></script>
<script>
//依赖包ngSanitize html标签解析包
angular.module('myApp',['ngSanitize'])
// $http是angular中的数据请求方式
.controller('demoCtrl',['$scope','$http',function($scope,$http){
//1.$http请求数据练习
/* $http({
url:"./test.json",
method:"get",
}).then(function(res){
console.log(res);
$scope.data=res.data;
}) */
//2.$http.get请求方式
/* $http.get("./test.json", { params:{a:1,b:2 }
}).then(function(res){
console.log(res);
$scope.data=res.data;
}) */
//3.$http.post请求方式(语法稍有不用,参数直接'{ }'包裹) ×报错
$http.post('./test.json').then(function(res){
console.log(res.data)
})
}])
</script>
</body>
</html>