本文内容来自开课吧相关视频。
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'}。