中止多个xhr请求

时间:2016-12-02 16:02:37

标签: javascript security xmlhttprequest

考虑这种情况:我有一个项目列表和分页,以便按块加载它们。在每个下一页上单击新的XHR调用以获取项目的新部分。当用户点击非常快时,我有很多xhrs,其中实际上没有必要,因为用户只想要最后点击的页面项目,并且他们也需要资源。因此,除了最后一个为每个请求调用xhr.abort()的挂起请求之外,我可以中止所有请求。问题是:中止多个xhrs是否安全?我读过服务器可能会认为它是某种攻击。如果是这样,用后端人检查哪些设置?

注意:使xhrs的函数已被去抖400毫秒。

1 个答案:

答案 0 :(得分:1)

在发送请求之前,最好在几百毫秒内对事件进行debuff,而不是取消待处理的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>

相关问题