ajax如何初始化,初始化ajax请求的最佳实践

博客探讨了JavaScript中setTimeout的使用以及如何在Ajax请求中设置时间戳。在beforeSend回调中定义的timestamp_last_check变量无法在函数外部访问,但通过在doPoll函数中重新设置,实现了在Ajax请求中传递该变量。文章还展示了如何定期执行Ajax请求以检查更新。
摘要由CSDN通过智能技术生成

尝试

setTimeout(function () {

var timestamp_last_check = 0; //declare here to make it available to data:

$.ajax({

'method': 'POST',

'url': '/ajax/request_news',

'beforeSend': function () {

alert('Before send')

date = new Date()

timestamp_last_check = Math.floor(date.getTime() / 1000); //set Value here

},

问题强>

var timestamp_last_check仅限于beforeSend:,因此无法在该区域外访问。

'beforeSend': function () {

alert('Before send')

date = new Date()

var timestamp_last_check = Math.floor(date.getTime() / 1000)

},

在OP的评论

之后更新

function doPoll() {

alert('GO POLL');

setTimeout(function () {

var date = new Date();

var timestamp_last_check = Math.floor(date.getTime() / 1000);//set value here

$.ajax({

'method': 'POST',

'url': '/ajax/request_news',

'data': {

'last_check': timestamp_last_check

},

'success': function (ret) {

ret = $.parseJSON(ret)

},

'complete': function () {

doPoll()

}

})

}, 5000)

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值