Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果需要花费大量时间加载,如何中止XMLHttpRequest?_Javascript_Reactjs_React Native_Xmlhttprequest - Fatal编程技术网

Javascript 如果需要花费大量时间加载,如何中止XMLHttpRequest?

Javascript 如果需要花费大量时间加载,如何中止XMLHttpRequest?,javascript,reactjs,react-native,xmlhttprequest,Javascript,Reactjs,React Native,Xmlhttprequest,我最近开始使用XMLHttpRequest。如果请求花费太多时间给出响应,是否有方法中止请求?还有一个问题,当我发出请求时,为什么我不能在XMLHttpRequest.onprogress中执行console.log let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(this.readyState === 4) resolve(something) } xhr.

我最近开始使用XMLHttpRequest。如果请求花费太多时间给出响应,是否有方法中止请求?还有一个问题,当我发出请求时,为什么我不能在XMLHttpRequest.onprogress中执行console.log

let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
       if(this.readyState === 4)
           resolve(something)
}
xhr.onprogress = function () {
   console.log("loading..") // not printing
}

 xhr.open('GET', url);
//headers
xhr.send();

要中止,只需使用
xhr.abort()
方法,它将取消您的请求。另外,您不希望它取消,除非它正在工作,因此您可以设置一个时间限制,如果没有检索到响应,将在该时间限制内执行中止

另外,获取一个变量
isReceived
,并将其设置为false。现在,如果收到响应,它将被设置为true,并且不会执行abort()方法。否则,如果未在所需时间内收到,则它将保持为false,并将被中止

let isReceived = false;
let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
       if(this.readyState === 4)
           isReceived = true;
           resolve(something)
}
xhr.onprogress = function () {
   console.log("loading..") // not printing
   setTimeout(function(){  
     if(!isReceived){
     xhr.abort(); 
    }
   }, 2000);
}

 xhr.open('GET', url);
//headers
xhr.send();

嗨,谢谢你的回答。在上面的代码中,我应该将这条语句放在哪里?如果AJAX操作成功,是否值得取消超时?我想如果它完成了就不能中止,但是不管结果如何,调用
abort()
仍然感觉有点脏。