这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。
直接用ajax调用不同域的数据:
调用的文件
文件内容
<html> <head> <title>跨域测试_ajax</title> <script src="/public/wechat/javascripts/jquery-2.0.3.min.js"></script> <script> $(function() { $("#but").click(function(){ $.ajax({ type:"post", url:"http://localhost:8081/category2.json", success:function(data){ /* console(data); */ $("#text").html(data); } }) }) }) </script> </head> <body> <button type="button" id="but">获取跨域的数据</button> <textarea id="text" style="width: 400px; height: 100px;"></textarea> </body> </html>
|
报错:Failed to load http://localhost:8081/category2.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9003' is therefore not allowed access.
跨域请求被拒绝,其实数据已经获取成功了,只不过是被浏览器给拒绝了
通过js引用将数据引进来:
<html> <head> <title>跨域测试-引用js片段的形式将数据引进来</title> <script src="/public/wechat/javascripts/jquery-2.0.3.min.js"></script> <script> //回调函数 function service (result) { var data = JSON.stringify(result); //json对象转成字符串 $("#text").val(data); } </script> </head> <body> 跨域的数据:<textarea id="text" style="width: 400px; height: 100px;"></textarea> <!-- 要在上面的回调函数、文本域标签加载完了再跨域引用 --> <script src='http://localhost:8081/category2.json'></script> </body> </html> |
页面
数据获取成功
jsonp就是用方式进行跨域请求的