AJAX-同源策略 跨域访问

## 同源策略

概述: 同源策略是浏览器的一种安全策略,视为同源是指域名,协议,端口完全相同。只有同源的地址才可以通过AJAX方式请求。同源或者不同源说的是两个地址的关系,不同源地址之间请求我们称之为跨域请求。

即是不同源地址之间,不能发送 AJAX 请求。

###2,寻找一个有效的方法 实现跨域请求

请求方url:http://www.lisi.com/ajax-02/day02/xinlang.html

响应方url:http://www.zhangsan.com/02_ajax/server/test.php

跨域方法如下:

 1     
 2     <!-- img link script iframe -->
 3     <!-- 尝试找到一种发送不同源的请求方式 -->
 4 
 5    <!--  校验目的:
 6     1,能发出去
 7     2,能收回来
 8 
 9     img 能够得到响应 但是不能得到字符串
10 
11     link 能够得到响应 但是会按照css来执行
12 
13     script 得到响应会按照 js 语法来执行 -->
14     <!-- 所以可以使用这个特点 使用jsonp 来实现跨域信息的获取 -->
15 
16     <!-- http://www.zhangsan.com/02_ajax/server/test.php -->
17 
18 
19     <img src="https://wx4.sinaimg.cn/mw690/671419afgy1g0ff9kv6zmj21sc2dskjm.jpg">
20 
21    <!--  <script id="script1" type="text/javascript" src="template-web.js">
22         window.onload =function() {
23         var script = document.getElementById('script');
24         console.log(1);
25         console.log(script);
26 
27        };
28     </script> -->
29 
30     <script type="text/javascript">
31         
32         var script =document.createElement('script');
33         script.src = "http://www.zhangsan.com/02_ajax/server/test.php";
34         document.body.appendChild(script);
35         console.log(script);
36 
37         
38         function foo(data) {
39              console.log(data);
40         }
41     </script>
42 
43 服务端返回: foo('var a = 123')

script: 使用script标签 和 jsonp (利用js代码执行特性)实现跨域。

猜你喜欢

转载自www.cnblogs.com/xixiaijunjun/p/10422998.html