如何在javascript中从[object HTMLDocument]获取内容

如何在javascript中从[object HTMLDocument]获取内容,javascript,html,ajax,xmlhttprequest,fetch-api,Javascript,Html,Ajax,Xmlhttprequest,Fetch Api,我试图从url获取一个HTML数据(我从字符串中解析它,因为链接到它的javascript文件不起作用),然后将响应加载到文档中。但是,当我在控制台中记录响应时,我会得到html内容,但在加载文档时它会显示[object HTMLDocument] 这是我的密码- fetch(url) 。然后(res=>res.text()) 。然后(数据=>{ 让parsedRes=(new window.DOMParser()).parseFromString(数据,“text/html”) process

我试图从url获取一个HTML数据(我从字符串中解析它,因为链接到它的javascript文件不起作用),然后将响应加载到文档中。但是,当我在控制台中记录响应时,我会得到html内容,但在加载文档时它会显示[object HTMLDocument]

这是我的密码-

fetch(url)
。然后(res=>res.text())
。然后(数据=>{
让parsedRes=(new window.DOMParser()).parseFromString(数据,“text/html”)
processData(解析数据、url)
});
函数processData(响应,urlPath){
console.log(响应)
document.querySelector(“html”).innerHTML=响应;
window.history.pushState({},“,urlPath);
};

如何实现这一点?

响应是一个文档对象,innerHTML需要一个字符串。您可以使用
响应
文档的内部html

fetch(`data:text/html;,\u003cscript src=”https://code.jquery.com/jquery-3.6.0.min.js“>\u003c/script>div{color:red;}
这是一个红色的div\u003cscript>$('div')。追加('(绿色span);\u003c/script>`)
。然后(res=>res.text())
。然后(数据=>{
让parsedRes=(new window.DOMParser()).parseFromString(数据,“text/html”)
setTimeout(函数(){
processData(parsedRes,'url');
}, 2500);
});
异步函数processData(响应,urlPath){
console.log(响应)
document.querySelector(“html”).innerHTML=response.querySelector(“html”).innerHTML;
var scripts=document.querySelectorAll(“脚本”);
对于(var i=0;i{
script.onload=()=>resolve(true);
script.onerror=()=>拒绝(false);
});
}
}
否则{
让script=document.createElement('script');
script.innerHTML=脚本[i].innerHTML;
脚本[i].parentNode.insertBefore(脚本,脚本[i]);
}
}
window.history.pushState({},“,urlPath);
};

这是原始div
响应
是一个文档对象,innerHTML需要一个字符串。您可以使用
响应
文档的内部html

fetch(`data:text/html;,\u003cscript src=”https://code.jquery.com/jquery-3.6.0.min.js“>\u003c/script>div{color:red;}
这是一个红色的div\u003cscript>$('div')。追加('(绿色span);\u003c/script>`)
。然后(res=>res.text())
。然后(数据=>{
让parsedRes=(new window.DOMParser()).parseFromString(数据,“text/html”)
setTimeout(函数(){
processData(parsedRes,'url');
}, 2500);
});
异步函数processData(响应,urlPath){
console.log(响应)
document.querySelector(“html”).innerHTML=response.querySelector(“html”).innerHTML;
var scripts=document.querySelectorAll(“脚本”);
对于(var i=0;i{
script.onload=()=>resolve(true);
script.onerror=()=>拒绝(false);
});
}
}
否则{
让script=document.createElement('script');
script.innerHTML=脚本[i].innerHTML;
脚本[i].parentNode.insertBefore(脚本,脚本[i]);
}
}
window.history.pushState({},“,urlPath);
};

这是原始div
它工作正常,但javascript文件似乎没有加载。你知道如何解决这个问题吗?因为innerHTML不会执行脚本,所以你必须找到它们并手动执行。它起作用了,但javascript文件似乎没有加载。你知道如何解决这个问题吗?因为innerHTML不会执行脚本,所以你必须找到它们并手动执行它们。