2016-12-02 186 views
0

请考虑这种情况:我有一个项目和分页列表来加载它们的块。在每个下一页上单击新的XHR呼叫以获取新的部分项目。当用户点击的速度非常快时,我有很多xhrs,其中实际上没有必要,因为用户只需要最后一次点击的页面项目,并且还需要资源。所以我可以放弃所有,但最后一个挂起的请求调用xhr.abort()为他们每个人。问题是:中止多个xhrs是否安全?我读过服务器可能认为它是某种攻击。如果是的话,什么设置与后端家伙检查?中止多个xhr请求

注意:使xhrs的功能已经消除400 ms。

+0

我个人采取无视点击的方法时,目前还主动要求,类似于虽然计时器点击时禁用提交按钮的过程。 – Archer

+0

或者,如果您检测到新的请求或取消呼叫,则会取消该请求,因此无法快速进行多次呼叫。 – epascarello

+0

点击发生的功能被消除,但我们的测试人员仍然每200毫秒同时点击一次,并且一旦反跳inerval被更改为400毫秒 - 每410毫秒一次等等。仍然有很多请求 –

回答

1

与其取消挂起的xhr请求,您最好在发送请求之前将您的事件减少几百毫秒。每次按下按钮时,你会重置延迟XHR请求

const button = document.querySelector('#button') 
 
const url = 'https://jsonplaceholder.typicode.com/posts/1' 
 

 
const request = (function() { 
 
    // save the current ajax request in the closure 
 
    let ajax = null 
 
    return function(url, params, cb) { 
 
    if (ajax) { 
 
     // if there is a current request cancel it 
 
     ajax.abort() 
 
     console.log('aborted ajax request') 
 
    } 
 
    // set a new xhr 
 
    ajax = new XMLHttpRequest 
 
    ajax.onreadystatechange = function() { 
 
     if (ajax.readyState === 4 && ajax.status === 200) { 
 
     // run the callback with the response 
 
     cb(JSON.parse(ajax.responseText)) 
 
     // remove the previous request 
 
     ajax = null 
 
     } 
 
    } 
 
    ajax.open('GET', url, true) 
 
    ajax.send(params) 
 
    } 
 
})() 
 

 
const clickCallback = debuff(function(e) { 
 
    console.log('clicked') 
 
    // make the xhr request 
 
    request(url, null, function(response) { 
 
    console.log('response', response) 
 
    }) 
 
}, 100) 
 
           
 
button.addEventListener('click', clickCallback, false) 
 

 
function debuff(fn, delay) { 
 
    let timer = null 
 
    return function(e) { 
 
    clearTimeout(timer) 
 
    timer = setTimeout(e => fn(e), delay || 250, e) 
 
    } 
 
}
<button id="button">debuffed click</button>

+0

谢谢,但其已执行,因为我在评论中写道,我仍然有案件,当我需要中止请求 –

+0

@OlenaHoral确定对不起,我没有看到。 – synthet1c

+0

@OlenaHoral我已经更新了我的答案。这将当前的ajax请求保存到'request'闭包中,并且如果有任何未完成的请求,则取消任何先前的请求。 – synthet1c