JavaScript跨域解决方式
平时工作中经常被JavaScript跨域问题所困扰,其实有很多种解决方式,下面给大家介绍常用的几种:
1.jsonp解决跨域问题
客户端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jsonp-跨域</title>
<script type="text/javascript" src="resources/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function callbackFn(data){
data = typeof data != 'string' ? JSON.stringify(data) : data;
console.log('callback:'+data);
}
function jsonpFn(){
$.ajax({
type:"get",
dataType:"jsonp",
url:"http://localhost:9393/ccy_server/server.jsp",
jsonpCallback:"callbackFn",
success:function(data){
data = typeof data != 'string' ? JSON.stringify(data) : data;
console.log('success.data:'+data);
}
});
}
function ajaxFn(){
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var url = "http://localhost:9393/ccy_server/server.jsp";
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
callbackFn(xmlhttp.responseText);
}
}
}
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
}
ajaxFn();
//jsonpFn();
</script>
</head>
<body> </body>
</html>
服务端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String result = "{\"name\":\"ccy\",\"age\":18,\"info\":{\"address\":\"wuhan\",\"interest\":\"playCards\"}}";
out.println("callbackFn("+result+")");
%>
相信大家对此种方式并不陌生,需要引用jquery库文件,并且要与服务端进行协调处理。
我先写了个简单的ajax调用非同源的异步请求直接报错
执行jsonpFn方法
成功获取服务端信息!
2.window.name解决跨域问题
在客户端浏览器中每个页面都有一个独立的窗口对象window,默认情况下window.name为空,在窗口的生命周期中,载入的所有页面共享一个window.name并且每个页面都有对此读写的权限,window.name会一直存在当前窗口,但存储的字符串不超过2M。
http://localhost:8383/ccy_client/window_name.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window.name-跨域</title>
<script type="text/javascript">
window.name = "我是 window.name 字符串";
setTimeout(function(){
window.location = "http://localhost:9393/ccy_server/window_name.html";
},2000);
</script>
</head>
<body> </body>
</html>
http://localhost:9393/ccy_server/window_name.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window.name-跨域</title>
<script type="text/javascript">
var str = window.name;
console.log('ccy_server.window_name:'+str);
</script>
</head>
<body> </body>
</html>
chrome打印信息
上面是以window.location跳转的方式获取window.name字符串信息,平时开发中经常需要异步获取,请继续往下看:
http://localhost:8383/ccy_client/window_name_iframe.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window.name-跨域</title>
</head>
<body>
<script type="text/javascript">
var boo = false;
var iframe = document.createElement('iframe');
var loadData = function() {
if (boo) {
var data = iframe.contentWindow.name; //获取window.name
console.log(data);
//销毁数据
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
} else {
boo = true;
iframe.contentWindow.location = ""; // 设置的代理文件,iframe重新载入
}
};
iframe.src = 'http://localhost:9393/ccy_server/window_name_iframe.html';
if (iframe.attachEvent) {
iframe.attachEvent('onload', loadData);
} else {
iframe.onload = loadData;
}
document.body.appendChild(iframe);
</script> </body>
</html>
http://localhost:9393/ccy_server/window_name_iframe.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window.name-跨域</title>
<script type="text/javascript">
window.name = '我是 http://localhost:9393/ccy_server/window_name_iframe.html';
</script>
</head>
<body> </body>
</html>
chrome打印信息
成功获取非同源地址的数据信息,主要是通过iframe的src属性,类似含有src属性的标签都可以成功处理跨域问题(img,script)
3.postMessage解决跨域问题
h5新特性,window.postMessage(msg,targetOrigin);
msg:传入的字符串信息
targetOrigin:目标源(协议主机端口有效)
同样借助iframe进行跨域操作
http://localhost:8383/ccy_client/postMessage.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>postMessage-跨域</title>
</head>
<body>
<iframe id="ifr" src="http://localhost:9393/ccy_server/postMessage.html" style="display: none;"></iframe>
<br>
<input id="txt" type="text" style="width:600px;height:70px;"/>
<br>
<input id="btn" type="button" value="获取9393数据" onclick="getData();" style="width:180px;height:60px;"/>
<script type="text/javascript">
var data;
function handleMsg(e){
e = e || event;
data = e.data;
console.log('8383:'+e.data);
}
if(window.addEventListener){
window.addEventListener('message', handleMsg);
}else{
window.attachEvent('onmessage', handleMsg);
}
function getData(){
document.getElementById('txt').value=data;
var msg = 'http://localhost:8383/ccy_client/postMessage.html';
window.frames[0].postMessage(msg, 'http://localhost:9393');
}
</script> </body>
</html>
http://localhost:9393/ccy_server/postMessage.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>postMessage-跨域</title>
</head>
<body>
<script type="text/javascript">
function handleMsg(e){
e = e || event;
console.log('9393:'+e.data);
}
if(window.addEventListener){
window.addEventListener('message', handleMsg);
}else{
window.attachEvent('onmessage', handleMsg);
}
window.onload = function(){
var msg = '我是 http://localhost:9393/ccy_server/postMessage.html';
window.parent.postMessage(msg, 'http://localhost:8383');
}
</script> </body>
</html>
chrome打印信息
点击“获取9393数据”
成功获取非同源数据,将非同源地址嵌入获取数据页面窗口。
4.Java解决跨域问题
通过客户端页面的ajax异步请求同源页面,再通过java的HttpURLConnect或者HttpClient进行转换即可,此处就不再赘述。
还有一种就是设置服务端的Header,我们果果乐园新版的api就是这么处理的。
5.参考资料
https://www.sojson.com/blog/121.html
https://www.jianshu.com/p/43ff69d076e3
JavaScript权威指南
欢迎纠错~~~
JavaScript跨域解决方式的更多相关文章
- JavaScript跨域解决方法大全
跨域的定义:JavaScript出于安全性考虑,同源策略机制对跨域访问做了限制.域仅仅是通过“URL的首部”字符串进行识别,“URL的首部”指window.location.protocol +win ...
- JavaScript跨域解决办法
在找到跨域解决办法之前,我们要先弄清楚一些基本概念 什么是跨域? 什么是“同源策略”? 跨文档消息通信 & 跨域请求数据 主域相同而子域不同 不同域名的跨域访问 什么是跨域? 简单地理解就是因 ...
- JS跨域解决方式 window.name
window.name 传输技术,原本是 Thomas Frank 用于解决 cookie 的一些劣势(每个域名 4 x 20 Kb 的限制.数据只能是字符串.设置和获取 cookie 语法的复杂等等 ...
- js跨域解决方式
什么是跨域? 概念:仅仅要协议.域名.port有不论什么一个不同,都被当作是不同的域.(所谓同源是指,域名.协议,port同样.),对于port和协议的不同,仅仅能通过后台来解决. URL 说明 是否 ...
- [转]JS跨域解决方式 window.name
本文转自:http://www.cnblogs.com/lichuntian/p/4909465.html window.name 传输技术,原本是 Thomas Frank 用于解决 cookie ...
- Javascript跨域请求的几种解决方法
什么情况下才会出现跨域? 假设域名是:http://www.example.com.cn/ 如果所请求的域名跟这个域名不致,这种情况就是跨域,由于跨域存在漏洞,所以一般来说正常的跨域请求方式是请求不到 ...
- jQuery(三) javascript跨域问题(JSONP解决)
加油~ --WH 一.什么是javascript跨域问题? 域:服务器域名,唯一标识(协议,域名,端口)必须保证一致,说明域相同 跨域:在一个服务器上,去访问另一个服务器上,并且得到另一个服务器返回回 ...
- JavaScript 跨域漫游
前言: 最近在公司做了几个项目都涉及到了iframe,也就是在这些iframe多次嵌套的项目中,我发现之前对iframe的认识还是比较不足的,所以就静下心来,好好整理总结了iframe的相关知识:&l ...
- 利用javascript跨域访问cookie之广告推广
在上一篇<说一说javascript跨域和jsonp>中,利用JSONP进行了跨域的数据访问,利用JS本身的跨域能力在远端生成HTML结构的方式完成了一个小广告. 在实际应用中, 跨域使用 ...
随机推荐
- MD5加密算法的Java版本
网上搜索Java实现MD5的资料很多,错误的也很多. 之前编写的一个阿里云直播鉴权原理算法需要用到MD5算法,网上找了几个,都是不行,浪费了时间,现在贴一个,做备用. import java.secu ...
- Xpath在选择器中正确,在代码中返回的是空列表问题
一.问题: 在进行爬虫的时候我们会用到xpath解析html文件,但是会有一种情况就是在xpath选择器中可以使用,但是在代码中就无法使用的情况. 二.原因: 1.是元素中有tbody的原因,这个元素 ...
- Linux环境部署项目引起Out of Memory Error: PermGen Space的解决方案
1. 背景 前几天,在搭建项目时遇到到一些问题,现在整理记录一下. Linux环境:Red Hat Enterprise Linux Server release 6.4: # 查看命令cat /et ...
- 使用GetAdaptersInfo时,网卡类型的值为71
使用GetAdaptersInfo时,网卡类型的值为71,代表无线网卡.
- 参考文献bib管理
比如在IEEE模板中,在当前目录添加 bib 文件reference.bib 在 \end{document} 之前加入 \bibliographystyle{IEEEtran} \bibliogra ...
- 第42章:MongoDB-集群--Sharding(分片)--单机的搭建
①配置服务器 在大型的集群中,建议配置3台配置服务器,就足够用了.启动配置服务器的方式: 1:先创建几个存放数据的文件夹,比如在前面的dbs下面创建confdb文件夹,然后在confdb下面创建con ...
- python3 与 Django 连接数据库报错:ImportError: No module named 'MySQLdb'
在 python2 中,使用 pip install mysql-python 进行安装连接MySQL的库,使用时 import MySQLdb 进行使用 在 python3 中,改变了连接库,改为了 ...
- RobotFramework+Selenium2软件安装教程
1.安装python 必须是 2.7 版本 设置环境变量:F:\software\Python27;F:\software\Python27\Scripts; 重启电脑: 2.安装wxPy ...
- stm32驱动12832液晶屏程序(ST7565R控制器)
LCD12832.c文件: #include"stm32f10x_lib.h" #include "OCM12232.h" void Lcd12232delay ...
- 2017CS231n学习笔记——计算机视觉的概述
本节课主要讲述了cs231n课程的背景和计算机视觉的历史,也主要介绍了目前很重要的一个计算机视觉数据集--IMAGENET. 更多内容参考我的AI学习之路 课程简介 这门课程是由stanford大学计 ...