[英]Is there a way to JSON.stringify an HTML dom object? [JavaScript]
I am trying to load in a external html file and stringify the contents within the body but can't seem to do so without it producing undesired results. 我正在尝试加载外部html文件并在正文中对内容进行字符串化处理,但如果不产生不希望的结果,似乎无法这样做。 Is there even a way to do this?
有没有办法做到这一点?
var xhr = new XMLHttpRequest();
function loadFile(){
xhr.open("GET", 'index.html');
xhr.responseType = "document";
xhr.send();
}
xhr.onload = function(data) {
myData = data;
myString = JSON.stringify(myData.srcElement.responseXML.body.children);
console.log(myString)
//logs: {"0":{},"length":1}
}
loadFile();
But what I need it to load is the actual div contents, ex: 但是我需要加载的是实际的div内容,例如:
//log: '<div id ='mydiv'>...</div>
What am I doing wrong? 我究竟做错了什么?
Your question is not very clear but I want to give it a try. 您的问题不是很清楚,但我想尝试一下。 Inspired from there: https://stackoverflow.com/a/7539198/1636522 .
从那里得到启发: https : //stackoverflow.com/a/7539198/1636522 Demo: http://jsfiddle.net/wared/fezc6tnt/ .
演示: http : //jsfiddle.net/wared/fezc6tnt/ 。
function string2dom (html) {
var iframe, doc;
iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.parentNode.removeChild(iframe);
doc.open();
doc.write(html);
doc.close();
return doc;
}
var dom = string2dom(''
+ '<html>'
+ '<head>'
+ '<title>test</title>'
+ '</head>'
+ '<body>'
+ '<div id="test">allo la <b>terre</b></div>'
+ '</body>'
+ '</html>'
);
document.body.innerHTML = (
dom.getElementById('test').innerHTML
);
I was able to figure this out by changing the response type to 'DOMString': 通过将响应类型更改为“ DOMString”,我能够弄清楚这一点:
function buildAd(file){
xhr.open("GET", file);
xhr.responseType = "DOMString";
xhr.send();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.