1. 设置请求超时时间: xhr.timeout, 如果超时, 请求会自动终止; 参数是毫秒;

2. 设置请求超时监听函数: xhr.ontimeout, 如果请求超时, 则会触发ontimeout事件的监听函数;

var xhr = new XMLHttpRequest(); 
var url = '/server'; 
 
xhr.ontimeout = function () { 
  console.error('The request for ' + url + ' timed out.'); 
}; 
 
xhr.onload = function() { 
  if (xhr.readyState === 4) { 
    if (xhr.status === 200) { 
      // 处理服务器返回的数据 
    } else { 
      console.error(xhr.statusText); 
    } 
  } 
}; 
 
xhr.open('GET', url, true); 
// 指定 10 秒钟超时 
xhr.timeout = 10 * 1000; 
xhr.send(null);

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

怎样获取从服务器返回的状态码和状态提示文本