温馨提示×

XMLHttpRequest如何设置超时时间

小樊
119
2024-06-19 16:14:06
栏目: 编程语言

在使用XMLHttpRequest对象发送请求时,可以通过设置timeout属性来定义超时时间,单位为毫秒。如果请求在超时时间内没有完成,则会触发timeout事件。

示例代码如下:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.com/api/data', true);
xhr.timeout = 5000; // 设置超时时间为5秒

xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    // 请求成功处理逻辑
  } else {
    // 请求失败处理逻辑
  }
};

xhr.ontimeout = function() {
  // 请求超时处理逻辑
};

xhr.send();

在上面的示例中,设置了xhr.timeout = 5000; 表示设置超时时间为5秒,如果请求在5秒内没有完成,则会触发ontimeout事件。

0