一说到ajax跨域。首先想到的就是jsonp 。
JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。
即使使用jQuery的jsonp方法,type设为POST,也会自动变为GET。
官方问题说明:
- “script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter,
- “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.
如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。
因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。
如果直接使用ajax访问,会有以下错误:
- XMLHttpRequest cannot load http://www.server.com/server.PHP. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.
被请求的Response header中加入:
- <?php
- // 指定允许其他域名访问
- header('Access-Control-Allow-Origin:*');
- // 响应类型
- header('Access-Control-Allow-Methods:POST');
- // 响应头设置
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
- ?>
ajax跨域访问代码案例:
例如:客户端域名:www.aaa.com 服务端域名:www.bbb.com
test.html 路径:http://www.aaa.com/test.html
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html;charset=utf-8">
- <title> 跨域测试 </title>
- <script src="//code.jquery.com/jquery.js"></script>
- </head>
- <body>
- <div id="show"></div>
- <script type="text/javascript">
- $.post("http://www.bbb.com/test.php",{name:"111",number:"222"})
- .done(function(data){
- document.getElementById("show").innerHTML = data.name + ' ' + data.number;
- });
- </script>
- </body>
- </html>
test.php 路径:http://www.bbb.com/test.php
- <?php
- $data= array(
- 'name' => isset($_POST['name'])? $_POST['name'] : '',
- 'number' => isset($_POST['number'])? $_POST['number'] : ''
- );
- header('content-type:application:json;charset=utf8');
- header('Access-Control-Allow-Origin:*');
- header('Access-Control-Allow-Methods:POST');
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
- echo json_encode($data);
- ?>
重要提示:
Access-Control-Allow-Origin:* 表示允许任何域名跨域访问
如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名
例如:
- header('Access-Control-Allow-Origin:http://www.aaa.com');
如果需要设置多个域名允许访问,这里需要用php处理一下;
例如:
允许 www.aaa1.com 与 www.aaa2.com 可以跨域访问:
- <?php
- $ret = array(
- 'name' => isset($_POST['name'])? $_POST['name'] : '',
- 'number' => isset($_POST['number'])? $_POST['number'] : ''
- );
- header('content-type:application:json;charset=utf8');
- $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
- $allow_origin = array(
- 'http://www.aaa1.com',
- 'http://www.aaa2.com'
- );
- if(in_array($origin, $allow_origin)){
- header('Access-Control-Allow-Origin:'.$origin);
- header('Access-Control-Allow-Methods:POST');
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
- }
- echo json_encode($ret);
- ?>
2018年06月30日 00:03:33 沙发
好棒,支持。
真心谢谢你的分享
捷径加拿大留学移民:http://canadaeasy.ca
2018年01月28日 16:33:11 板凳
非常棒
2018年03月21日 16:08:07 1层
@未知的旅程 很nice啊