由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取另一个源加载的文档的属性。

特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接收罢了。

浏览器同源策略并不是对所有的请求均制约:

  • 制约:XmlHttpRequest
  • 不制约:img、iframe、script等具有src属性的标签

跨域,跨域名访问,如:http://www.c1.com域名向http://www.cw.com域名发送请求。

1. JSONP实现跨域请求

JSONP(JSONP-JSON with Padding是JSON的一种“使用模式”),是利用script标签的src属性(浏览器允许script标签跨域)。

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 
 9     <p>
10         <input type="button" onclick="Jsonp1();"  value='提交'/>
11     </p>
12 
13     <p>
14         <input type="button" onclick="Jsonp2();" value='提交'/>
15     </p>
16 
17     <script type="text/javascript" src="jquery-1.12.4.js"></script>
18     <script>
19         function Jsonp1(){
20             var tag = document.createElement('script');
21             tag.src = "http://c2.com:8000/test/";
22             document.head.appendChild(tag);
23             document.head.removeChild(tag);
24 
25         }
26 
27         function Jsonp2(){
28             $.ajax({
29                 url: "http://c2.com:8000/test/",
30                 type: 'GET',
31                 dataType: 'JSONP',
32                 success: function(data, statusText, xmlHttpRequest){
33                     console.log(data);
34                 }
35             })
36         }
37 
38 
39     </script>
40 </body>
41 </html>
42 
43 基于JSONP实现跨域Ajax - Demo
基于JSONP实现跨域Ajax -Demo

相关文章: