在瀏覽器JavaScript中創建Document的辦法


1. 使用XMLHttpRequest

這種方法主要涉及XMLHttpRequest的兩個屬性responseType與response。在調用XMLHttpRequest實例的open方法之后並且在調用send方法之前,將responseType的屬性值設置為字符串"document",然后當響應成功后XMLHttpRequest實例的response屬性值便是一個Document實例,但是如果響應類型不匹配的話屬性值則是null 

示例

 1 let xml = new XMLHttpRequest();
 2 
 3 xml.onload = () => {
 4 
 5 if (xml.status >= 200 && xml.status <= 299) {
 6 
 7 console.log(xml.response);
 8 
 9 }
10 
11 };
12 
13 xml.open("GET", "/");
14 
15 xml.responseType = "document";
16 
17 xml.send();

2.使用DOMParser對象 

示例

let doc = (new DOMParser).parseFromString("需要將其解析為Document的字符串", "text/html");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM