跨域
- 1.什么是跨域?
- 不同域名之間進行數據的訪問。會造成跨域問題。導致的結果就是拿不到數據
http://localhost/day2/06-%E8%B7%A8%E5%9F%9F.html
https://api.douban.com/v2/book/1220562
- 如何區分是否跨域?
就看是否同源。(要求:協議,端口號,主機地址相同)
不同源就是屬于跨域。 - 2.是誰造成的跨域?
- 是瀏覽器造成的跨域,其實數據已經到了瀏覽器當中,只不過,瀏覽器沒有把數據傳遞過來。
- 3.為什么要有跨域?
- 出于安全考慮。(默認情況下不允許外界的網站向本網站當中注入數據)
- 4.如何解決跨域?
- 使用jsonp (jsonp是解決跨域的一種方案。)
- 5.jsonp是ajax嗎?
- jsonp是解決跨域的一種方案。
- ajax它是js異步請求一種技術。(xhr對象)
- 6.說一下jsonp解決跨域的原理?
- 1.在本地當中定義一個方法名gxq
- 2.定義"<script src="myPhpFile.php?callback=gxq">" 在發送請求時,把函數名稱傳遞給服務器
------------上面2步是前端做的--------------
------------下面2步是后端做的-------------- - 3.要在服務器當中接收傳遞的參數 $fn = $_GET['callback'];
-
4.服務echo 方法名稱+('參數'),下面的1就是服務器傳遞的參數到客戶端;
- 注意:src可以訪問任何地址。
angular跨域
<script src="angular.js"></script>
<script>
//1.創建模板
var app = angular.module('app', []);
//2.創建控制器
app.controller('xmgController', ['$scope','$http', function ($scope,$http) {
$http({
url:'https://api.douban.com/v2/book/1220562', //訪問的url地址
method:'jsonp', //訪問方式
params:{
callback:'JSON_CALLBACK' //傳遞過去的參數
}
}).success(function (res) {
alert(res);
}).error(function (error) {
});
}]);
//3.綁定模塊
//4.綁定控制器
</script>
</head>
<body ng-app="app" ng-controller="xmgController">
</body>
angular1.6版本之后跨域
<script src="angular1.6.js"></script>
<script>
//1.創建模板
var app = angular.module('app', []);
//設置一個白名單。
app.config(['$sceDelegateProvider',function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://api.douban.com/**']);//!*當前文件代表所有文件 **所有文件夾下的所有文件。
}]);
//2.創建控制器
app.controller('xmgController', ['$scope','$http', function ($scope,$http) {
$http({
url:'https://api.douban.com/v2/book/1220562',
method:'jsonp',
}).then(function (res) {
}).catch(function () {
});
}]);
//3.綁定模塊
//4.綁定控制器
</script>
</head>
<body ng-app="app" ng-controller="xmgController">
</body>
使用php做橋接獲取數據
- 1.在qwl.php服務器中向某個接口獲取數據
$url = "https://api.douban.com/v2/book/1220562"; //獲取數據到服務器
echo file_get_contents($url); //顯示出來
- 2.在html客戶端中向qwl.php服務器發送請求獲取數據
<script src="angular.js"></script>
<script>
//1.創建模板
var app = angular.module('app', []);
//2.創建控制器
app.controller('xmgController', ['$scope','$http', function ($scope,$http) {
$http({
url:'qwl.php', //向誰訪問數據
method:'get' //用什么方式訪問
}).success(function (res) {
console.log(res);
}).error(function (error) {
});
}]);
//3.綁定模塊
//4.綁定控制器
</script>
</head>
<body ng-app="app" ng-controller="xmgController">
</body>