angularjs 中$http几种常用的请求方式

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>

转载于:https://my.oschina.net/shuaihong/blog/1542172

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值