跳到主要内容

跨域请求

后端设置返回头

res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Content-type,Content-Length,Authorization,Accept,X-Requested-Width"
);
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

示例

function crossDomain(url, fn) {
iframe = document.createElement("iframe");
iframe.style.display = "none";
var state = 0;

iframe.onload = function () {
if (state === 1) {
fn(iframe.contentWindow.name);
iframe.contentWindow.document.write("");
iframe.contentWindow.close();
document.body.removeChild(iframe);
} else if (state === 0) {
state = 1;
iframe.contentWindow.location = "www.baidu.com/proxy.html";
}
};

iframe.src = url;
document.body.appendChild(iframe);
}

// 调用
// 服务器地址
var url = "www.baidu.com/data.php";
crossDomain(url, function (data) {
// 处理数据 data就是window.name的值(string)
var data = JSON.parse(iframe.contentWindow.name);
console.log(data);
});
window.onload = function () {
var xhr = new XMLHttpRequest();
xhr.open("get", "https://a1.cnblogs.com/units/image/C2/creative");
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.response);
};

var proxy = function (url, callback) {
var state = 0;
var iframe = document.createElement("iframe");
var img = document.createElement("span");
document.body.appendChild(img);
// 加载跨域页面
iframe.src = url;

// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
iframe.onload = function () {
console.log(1);
};
document.body.appendChild(iframe);

// 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)
function destoryFrame() {
iframe.contentWindow.document.write("");
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};

// 请求跨域b页面数据
proxy("https://a1.cnblogs.com", function (data) {
alert(data);
});
};