1、在前端請(qǐng)求ajax的時(shí)候會(huì)遇到跨域的問題,不能夠請(qǐng)求到數(shù)據(jù)拔恰,需要搭建一下中間層褪尝,使用express來請(qǐng)求ajax數(shù)據(jù)然后前端再去請(qǐng)求后臺(tái)返回的數(shù)據(jù)闹获,這樣就不會(huì)遇到跨域問題,express代碼如下:
var ? express=require('express');
var ? router=express.Router();
var ? http=require('http');//引入http模塊
//后臺(tái)解決跨域問題
router.all('*',function(req,res,next) {
res.header("Access-Control-Allow-Origin","*");
res.header('Access-Control-Allow-Methods','PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers","X-Requested-With");
res.header('Access-Control-Allow-Headers','Content-Type');
next();
});
// 輪播的接口
// localhost:3000/lunbo
router.get('/lunbo',function(req,res) {
varpage=req.query.page;
varcount=req.query.count;
// 要去請(qǐng)求? 賣座網(wǎng)的接口
// http://m.maizuo.com/v4/api/billboard/home?__t=1500253189212
vartime=newDate().getTime();
http.get('http://m.maizuo.com/v4/api/billboard/home?__t='+time,function(response) {
vardata='';
response.on('data',function(chunk) {
data+=chunk;
})
response.on('end',function() {
res.send(data);
})
})
})
2河哑、上拉刷新的請(qǐng)求的ajax不能夠每次自動(dòng)加1的操作避诽,后來做了監(jiān)聽滾動(dòng)事件的函數(shù),在生命周期里面進(jìn)行加1操作后在滾動(dòng)的時(shí)候再次請(qǐng)求ajax璃谨,當(dāng)滾動(dòng)的高度和當(dāng)前頁面高度進(jìn)行對(duì)比時(shí)候在去請(qǐng)求沙庐。代碼如下:
componentDidMount() {
window.addEventListener('scroll',this.handleScroll);
// var page = this.props.page
varthat=this;
$.get('http://localhost:8080/come_play?page='+page+'&count=7',function(res) {
if(res) {
vardata=JSON.parse(res).data.films;
that.props.getComeplay(data);
page++;
}
})
}
//獲取滾動(dòng)數(shù)據(jù)
handleScroll=()=>{
console.log(flag)
varlist=this.props.come_play;//獲取state的數(shù)據(jù)
varfilmes=[];//用來接收新的數(shù)據(jù)
varthat=this;//改變一下this指向
vartop=(document.documentElement.scrollTop||document.body.scrollTop)+50;//頁面的滾動(dòng)
console.log(top)
varheight=document.documentElement.clientHeight;
varnowheight=200+height*(page-3);
console.log(nowheight)
// console.log(height)
if(top>nowheight&&flag) {
flag=false;
$.get('http://localhost:8080/come_play?page='+page+'&count=7',function(res) {
if(res) {
vardata=JSON.parse(res).data.films;
varfilme=list.concat(data);
varset=newSet(filme);
filmes=newArray(...set);//數(shù)組去重
that.props.getComeplay(filmes);
flag=true;
}else{
flag=false;
}
})
page++;//頁數(shù)+1
}else{
flag=true;
}
}
//銷毀時(shí)
componentWillUnmount() {
window.removeEventListener('scroll',this.handleScroll);
}