JSONP
1.浏览器对<script>,<link>,<img>等加载脚本,样式表,图片等资源的标签没有同源限制,而且资源加载后在没有阻塞的情况下会立即执行。利用script的这种特性可以动态插入一个script标签
<script src="https://localhost:8080/login?callback=jsonpCallback"></script>
<script>
function jsonpCallback(result) {
//alert(result);
for(var i in result) {
alert(i+":"+result[i]);
}
}
</script>
2.另外jquery也已经内部实现了跨域
$.ajax({
url:"https://localhost:8080/login",
data:{
name:"ccc",
email:"[email protected]"
},
type:"get",
datatype:"json",
success:function(result){
if(result!=null) {
console.log(result)
}
}
});
CROS
CORS需要浏览器和服务器同时支持,下面是我本地实现的一个小例子
客户端
var xmlhttp=new XMLHttpRequest(); if (!xmlhttp) { alert("创建xmlhttp对象异常!"); return false; } var url = "http://localhost:8000/cros"; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.onreadystatechange = function () { console.log("onreadystatechange and readyState:"+xmlhttp.readyState+", status:"+xmlhttp.status); if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { document.write(xmlhttp.responseText); } } } xmlhttp.send();
服务器端nodejs
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin':'http://localhost:63342'/*, 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'*/ }); res.write('cors'); res.end();
//readyState属性指出了XMLHttpRequest对象在发送/接收数据过程中所处的几个状态。XMLHttpRequest对象会经历5种不同的状态。
//0:未初始化。对象已经创建,但还未初始化,即还没调用open方法;
//1:已打开。对象已经创建并初始化,但还未调用send方法;
//2:已发送。已经调用send 方法,但该对象正在等待状态码和头的返回;
//3:正在接收。已经接收了部分数据,但还不能使用该对象的属性和方法,因为状态和响应头不完整;
//4:已加载。所有数据接收完毕