解决Ajax不能跨域的方法

1.  Ajax不能跨域请求的原因

同源策略(Same Origin Policy),是一种约定,该约定阻止当前脚本获取或者操作另一个域下的内容。所有支持Javascript的浏览器都支持同源策略,也就是说浏览器可以隔离来自不同源的内容,阻止跨域请求的发生。

2. 解决方法

(1) CORS

在被请求的脚本中使用header()函数设置http响应,从而使得跨域请求能够发生:

header(“Access-Control-Allow-Origin:*”);

这一方法称为CORS(Cross-Origin Resource Sharing),是w3c的工作草案。

(2) 使用Jsonp (Json with padding)

jsonp的原理是通过script标签的src属性来请求不同源的脚本。

步骤:

1) 创建script标签,设置src属性

2) 定义回调函数

3) 在被请求的php脚本中执行回调函数

4) 在回调函数中处理返回数据

 

发送跨域请求的html页面:

 1 <script type="text/javascript">
 2     function crossDomain()
 3     {
 4         //1.创建script标签,设置src属性
 5         var script = document.createElement('script');
 6         //在script标签的src属性中发送跨域请求
 7         //传递get参数 --> 回调函数的名字
 8         script.src = 'http://www.another.com/index.php?name=Jonas&fn=say';
 9         document.getElementsByTagName('head')[0].appendChild(script);
10     }
11 
12     //2.定义回调函数
13     function say(data)
14     {
15         //4.处理返回数据
16         console.log(data);
17     }
18 </script>

  接收跨域请求的php页面: 要执行回调函数

1 <?php 
2 //3.执行回调函数,将返回数据以参数的形式传给回调函数
3 $data = json_encode(array('msg' => 'hello world'));
4 echo $_GET['fn'] . "({$data})";
5 ?>

 

posted @ 2016-05-20 23:45  Mozshaw  阅读(4725)  评论(0)    收藏  举报