简体   繁体   English

使用XMLHttpRequest缓存页面

[英]Cache pages using XMLHttpRequest

Everything is and is run on the same domain in the latest versions of the major browsers. 在最新版本的主要浏览器中,所有内容都并且都在同一个域上运行。

 var xmlhttp = new XMLHttpRequest();
 var sites = ["/page1", "/page2", "/page3"];
 var cache = {};

 function xhrStart(url) {
   xmlhttp.open("GET", url, true);
   xmlhttp.send();
 }

 function isOkXhr() {
   return (xmlhttp.readyState == 4 &&
     (xmlhttp.status >= 200 && xmlhttp.status < 300));
 }

 function reload() {
   var len = sites.length;
   var i;
   for (i = 0; i < len; i++) {
     var url = sites[i];

     xmlhttp.onreadystatechange = function() {
       if (isOkXhr())
         cache[url] = xmlhttp.responseText;
     }
     xhrStart(url);
   }
 }

Reload function should be to cache all pages, but in fact all queries return Aborted in the debugger, except the last one. 重新加载功能应该是缓存所有页面,但实际上所有查询都在调试器中返回“异常终止”,最后一个除外。 What could be the problem? 可能是什么问题呢?

You are using one XHR object and keep writing over it in the loop. 您正在使用一个XHR对象,并在循环中继续对其进行写入。 When you call open() it aborts the previous request. 当您调用open()时,它将中止上一个请求。 The for loop does not wait for the request. for循环不等待请求。

Either create a new XHR request or wait til the other request is done before you make the next request. 创建新的XHR请求或等待直到另一个请求完成,然后再发出下一个请求。

var sites = ["/page1", "/page2", "/page3"];
var cache = {};

function xhrStart(url) {
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", url, true);
   xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4) {
           if(xmlhttp.status >= 200 && xmlhttp.status < 300) {
               cache[url] = xmlhttp.responseText;
           } else {
               //what are you going to do for error?
           }
       }       
   };
   xmlhttp.send();
}

for (var i = 0; i < sites.length; i++) {
    var url = sites[i];
    xhrStart(url);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM