2019独角兽企业重金招聘Python工程师标准>>>
javascript中有同源策略,javascript存在跨域通信的问题。典型例子如:Ajax无法直接请求跨域的普通文件,存在跨域无权限访问的问题。
几种常见的解决方法:
1.JSONP 2. window.name+frame 3.document.domain + iframe 4.iframe+location.hash 5.HTML5 postMessage 方法
一、JSONP
web页面上只有
本域代理页面为proxy.html,(也可以直接设置一个空白页面about:blank)
跨域页面:b.html:
四、document.domain + iframe
原理:针对主域相同而子域不同的两个页面,可以通过设置document.domain=“主域” 来解决。
将 http://www.f.com/a.html 和 http://m.f.com/b.html 都设置document.domain="f.com",然后在a.html中通过iframe加载b.html,则a.html 页面可以通过iframe.contentDocument.getElementById("id"); 来获取b页面数据。
五、iframe+location.hash
原理:改变页面hash不会导致页面刷新,所以通过添加或改变iframe的src链接的hash值来进行跨域传递数据
a页面创建iframe跨域请求b页面,请求参数置于hash中,b页面从location.hash中获取请求参数生成响应数据,a 和b跨域所以b页面中无法通过parent对象改变a页面的loaction.hash的值。所以需要在b.html中动态创建iframe加载一个和a同域的c页面,将响应数据置于c的loaction.hash中,然后在c页面中则可以通过parent.parent来访问a页面并通过loaction.hash来传递远程页面的返回值
缺点:数据大小有限,并且数据直接暴露在url中