微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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",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://www.jb51.cc/angularjs/146075.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐