使用 XMLHttpRequest 获取网页,但只获取 html 的一部分

using XMLHttpRequest to get a web page but only get one part of the html

本文关键字:获取 html 一部分 XMLHttpRequest 网页 使用      更新时间:2023-09-26

我使用下面的代码来获取网页(html)

var  htmlString=null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");//can change to any web address 
xhr.onreadystatechange = function() {
     htmlString=htmlString+xhr.responseText;
     if(xhr.statusText=="200 OK'r" ){ 
       log (global.htmlString.length);
     }
}

但它总是得到页面的一部分,而不是整个HTML代码是否有任何参数来设置返回 html 代码的长度?

欢迎您的评论

将有多个readystatechange事件。只有在xhr.readyState === XMLHttpRequest.DONE === 4 时,请求才会完全完成。

此外,htmlString = null; ...; htmlString=htmlString+xhr.responseText;在很多方面都是假的。第一次它会做htmlString = null + "text" === "nulltext.之后,它将一次又一次地添加.responseText(到目前为止检索到的),同时通过状态。

另外,在相关说明中,您应该检查 xhr.status == 200 ,而不是xhr.statusText == randomString 。在 200 的情况下,Web 服务器不一定发送"OK"。

阅读XMLHttpRequest文档。

像这样的东西应该更好用:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 /* DONE */) {
     console.log(xhr.responseText.length);
     // Do something with it...
  }
}
xhr.send();