一、xhr超时
XHR对象的timeout属性等于一个整数,表示多少毫秒后,如果请求仍然没有得到结果,就会自动终止。该属性默认等于0,表示没有时间限制。
如果请求超时,将触发ontimeout事件(IE8不支持)
var xhr = new XMLHttpRequest();
xhr.open('post','test.php',true);
xhr.ontimeout = function(){
console.log('The request timed out.');
}
xhr.timeout = 1000;
xhr.send();
二、跨域请求
xhr.withCredentials = true;
xhr.setRequestHeader('X-Request-With', "XMLHttpRequest");
只有客户端设置这个值还不能跨域,还需要服务端同意才行。
Access-Control-Allow-Credentials: true;
还有一点要注意的,返回头Access-Control-Allow-Origin的值不能为星号,必须是指定的域,否则cookie等认证信息也是发送不了。
三、优化
使用AJAX接收数据时,由于网络和数据大小的原因,并不是立刻就可以在页面中显示出来。所以,更好的做法是,在接受数据的过程中,显示一个类似loading的小图片,并且禁用按钮;当数据完全接收后,再隐藏该图片,并启用按钮
四、其他
1.停止当前请求
xhr.abort();
2.把HTTP请求的所有响应首部作为键/值对返回
xhr.getAllResponseHeaders();
3.返回指定首部的串值
xhr.getResponseHeader("header");
4.把指定首部设置为所提供的值
xhr.setRequestHeader("header", "value");//在设置任何首部之前必须先调用open()。设置header并和请求一起发送 ('post'方法一定要 )
5.监听文件上传进度
xhr.upload.addEventListener("progress", function(e){...}, false);