xhr状态与循环结合

时间:2012-11-30 23:18:43

标签: javascript google-chrome xmlhttprequest

我正在尝试在images页面中编写有效html的网址(存在的图片)。 这是在变量urls中添加的输入图像列表: 网址是现有和不存在的Google产品图标的网址,例如

var urls = [
"https://www.google.com/images/icons/product/chart-32.png",
"https://www.google.com/images/icons/product/docs-32.png",
"https://www.google.com/images/icons/product/drive-32.png",
"https://www.google.com/images/icons/product/googlemail-32.png",
"https://www.google.com/images/icons/product/dropbox-32.png",
"https://www.google.com/images/icons/product/reader-32.png",
"https://www.google.com/images/icons/product/test-32.png",
"https://www.google.com/images/icons/product/microsoft-32.png",
"https://www.google.com/images/icons/product/chat-32.png",
"https://www.google.com/images/icons/product/hangouts-32.png",
"https://www.google.com/images/icons/product/maps-32.png",
"https://www.google.com/images/icons/product/map_maker-32.png",
"https://www.google.com/images/icons/product/apple-32.png",
"https://www.google.com/images/icons/product/latitude-32.png",
"https://www.google.com/images/icons/product/sketchup-32.png",
"https://www.google.com/images/icons/product/skymap-32.png",
"https://www.google.com/images/icons/product/google_favicon-32.png",
"https://www.google.com/images/icons/product/mobile_app-32.png",
"https://www.google.com/images/icons/product/mobileapp-32.png",
"https://www.google.com/images/icons/product/goggles-32.png"
];

要检查并记下文档中的图像URL,我使用: 当你获得https://www.google.com/的许可时,完全正常的东西 因此,当人们想要验证这一点时,请使用https://www.google.com/

上的js控制台
var xhr = {};
for(var i = urls.length; i-- ; i>0){
  xhr[i] = new XMLHttpRequest();
  xhr[i].open('GET',urls[i]);
  xhr[i].onload = write();
  function write() { 
       document.write(urls[i] + "<br>")
    }
  xhr[i].send(null);
  }

现在只编写有效的网址(包含png图标的网址。因此chart-32.png有效,但dropbox-32.png无效,我尝试了此代码:

var xhr = {};
for(var i = urls.length; i-- ; i>0){
  xhr[i] = new XMLHttpRequest();
  xhr[i].open('GET',urls[i]);
  xhr[i].onload = write();
  function write() { 
    if(xhr[i].status != 404){
       document.write(urls[i] + "<br>")
       }
    }
  xhr[i].send(null);
  }

但由于某些原因,只有当我将其限制为有效的png时,它才会在chrome中出现此错误:     错误:InvalidStateError:DOM异常11

有谁知道我做错了什么?和/或如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

Ajax-sync不需要“onload回调”。

调整此行:xhr[i].open('GET',urls[i]);

修复: xhr[i].open('GET',urls[i], false); - 避免错误

或者document.write替换document.getElement*(碰巧想要使用async-mode

同步模式Ajax,例如:

var r = new XMLHttpRequest();
    r.open("GET", "http://www.example.com", false);//Sync mode
    r.send(null);
    if (r.readyState===4 && r.status===200) {
        document.write(**content**);
    }

遵循此规则(即使它不是ajax):

  • document.write使用sync-mode。
  • 使用ascync-mode
  • document.getElement*getElementByIdgetElementsByTagNamegetElementsByClassName ...)。