0

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

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上的 js 控制台://www.google.com/

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 Exception 11

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

4

1 回答 1

1

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

调整这条线:xhr[i].open('GET',urls[i]);

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

或者替换document.writedocument.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与同步模式。
  • document.getElement*( getElementById, getElementsByTagName, getElementsByClassName...) 与异步模式。
于 2012-11-30T23:24:36.240 回答