angular $http 的JSONP实例

本文内容来自开课吧相关视频。

JSONP主要就是为了解决跨域问题。

angular中关于jsonp使用因为版本的不同而有差异,主要是1.6.4以前和以后。

1.6.4以前

<!DOCTYPE html>
<html lang="en" ng-app='test'>
<head>
	<meta charset="UTF-8">
	<title>angular 老版本 jsonp</title>
	<script src='angular-1.5.8.js'></script>
	<script>
	let mod = angular.module('test', []);

	mod.controller('main', function($scope, $http){
		$scope.word='';
		$scope.arr = [];

		$scope.$watch('word', function(){
			$http.jsonp(`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${$scope.word}&cb=JSON_CALLBACK`)
			.then(res=>{
				$scope.arr=res.data.s;
			}, ()=>{
				alert('error!!!')
			});
		})
		
	})
	</script>
</head>
<body ng-controller='main'>
	<input type="text" ng-model='word'>
	<ul>
		<li ng-repeat='a in arr'>{{a}}</li>
	</ul>
</body>
</html>

$http.jsonp(请求地址).then();

请求地址:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${$scope.word}&cb=JSON_CALLBACK

其中:wd=${$scope.word}是wd根据model中的$scope.word值

cb=JSON_CALLBACK是回调函数JSON_CALLBACK占位。

1.6.4以后

<!DOCTYPE html>
<html lang="en" ng-app='test'>
<head>
	<meta charset="UTF-8">
	<title>angular 1.6.4以后jsonp</title>
	<script src='angular.js'></script>
	<script>
		let mod = angular.module('test', []);

		mod.controller('main', function($scope, $http, $sce){
			$scope.arr = [];
			$scope.word = '';
	
			$scope.$watch('word',function(){

				let res = $sce.trustAsResourceUrl(`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${$scope.word}`);

				$http.jsonp(res,{jsonpCallbackParam:'cb'})
				.then(res=>{
					$scope.arr=res.data.s
				},()=>{
					alert('error!!!!')
				})
			});
		})
	</script>
</head>
<body ng-controller='main'>
	<input type="text" ng-model='word'>
	<ul>
		<li ng-repeat='a in arr'>{{a}}</li>
	</ul>
</body>
</html>

let res = $sce.trustAsResourceUrl(`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${$scope.word}`);

$http.jsonp(res,{jsonpCallbackParam:'cb'}) .then();

jsonp不是很安全,就引入$sce依赖。

使用$sce.trustAsResourceUrl(路径)告诉angular是安全的。

在$http.jsonp中添加{jsonpCallbackParam:'cb'}。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值