我们以两个主域名或者一个主域名+一个二级域名为例,均可演示跨域问题。
- 客户端 a.com
- 服务端 b.com或者s.a.com
- angularJs版本 V1.2.25
接下来我们先看客户端是如何请求数据的
注意哦,我们的代码是写在a.com域名下面的
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title></title>
<script src="./angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('appCtrl', ['$scope','$http', function ($scope,$http) {
$http({ method: 'JSONP', url: 'http://www.b.com/test.php?callback=JSON_CALLBACK', }).success(function (msg) { console.log(msg); }); //或者 $http .jsonp('http://www.b.com/test.php?callback=JSON_CALLBACK') .success(function (msg){ console.log(msg); }); }]); </script> </head> <body> </body> </html>
我们看到,这里是直接以jsonp的形式进行跨域请求的,其操作同jquery中对跨域的请求方式如出一辙。注意,我们的callback是固定的,即JSON_CALLBACK,尽量不要去做任何改动
我们再看服务端b.com中的test.php对请求数据的处理方式,这里以原生php的方式做参考
$callBack = isset($_GET['callback']) ? $_GET['callback'] : DEFAULT_CALLBACK;
exit($callBack.'('.json_encode($data).')');