有没有一种方法可以将 HTML dom 对象转换为 JSON 字符串?[JavaScript]

3

我正在尝试加载外部的HTML文件,并将其内容转换为字符串,但是似乎无法实现而不产生不良后果。这是否有可能呢?

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();

但我需要加载的是实际的div内容,例如:
//log: '<div id ='mydiv'>...</div>

我做错了什么?

你需要将想要的内容提取到自己的JavaScript数据结构中,然后对其进行字符串化。内置的序列化程序无法直接处理DOM。 - Pointy
使用 document.body.innerHTML。 - Raghavendra
如果你只想要实际的div内容,那么你不需要使用JSON.stringify。相反,可以这样做: myString = myData.srcElement.responseXML.body.children; - kennasoft
@raghavendra 我需要将值创建为字符串,以便我可以替换一些值或ID、属性、文本等。 - user3612986
2个回答

1
我通过将响应类型更改为“DOMString”来解决了这个问题:
function buildAd(file){
    xhr.open("GET", file);
    xhr.responseType = "DOMString";
    xhr.send();
}

跨浏览器兼容? - user1636522

0

您的问题不是很清楚,但我想试着回答一下。灵感来自这里:https://dev59.com/Yms05IYBdhLWcg3wD9wB#7539198。演示: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
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接