JSONP:
前端代码:
$('.change').addEventListener('click', function(){
var script = document.createElement('script');
script.src = 'http://jrg.com/getNews?callback=addSomeNwes';
document.head.appendChild(script);
document.head.removeChild(script);
})
function addSomeNwes(news){
……
}
function $(id){
return document.querySelector(id);
}
后台node.js代码:
app.get('/getNews', function(req, res){
var news = [
"高考加油",
"欢乐颂",
"苹果或将微信下架",
"厉害了小姐姐",
"11岁少女酷似刘诗诗",
"楚乔转",
"欢乐颂2",
"高考作文",
"北电侯良平",
"这一刻的时光"
]
var data = [];
for(var i=0; i<3; i++){
var index = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index, 1);//删除已选数据,避免重复
}
var cback = req.query.callback;
if(cback){
res.send(cback + '('+ JSON.stringify(data) + ')');
}else{
res.send(data);//如果没有callback就直接返回数据
}
})
CORS方法:
前端代码与AJAX并无不同,只是在后端需要添加:
res.header("Access-Control-Allow-Origin", "发送请求的域名");
//若为*,则代表任何人发送请求过来,我都将同意返回数据给他
res.header("Access-Control-Allow-Origin", "*");
app.get('/getNews', function(req, res){
var news = [
"高考加油",
"欢乐颂",
"苹果或将微信下架",
"厉害了小姐姐",
"楚乔转",
"欢乐颂2",
"高考作文",
"北电侯良平",
"这一刻的时光"
]
var data = [];
for(var i=0; i<3; i++){
var index = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index, 1);
}
res.header("Access-Control-Allow-Origin", "http://a.jrg.com:8080");
//res.header("Access-Control-Allow-Origin", "*");
res.send(data);
})
降域
//URL: http://a.jrg.com:8080/a.html
document.domain='jrg.com';
//URL: http://b.jrg.com:8080/b.html
document.domain='jrg.com';