有没有办法让JSON.stringify一个HTML DOM对象? [JavaScript的] [英] Is there a way to JSON.stringify an HTML dom object? [JavaScript]

查看:337
本文介绍了有没有办法让JSON.stringify一个HTML DOM对象? [JavaScript的]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图加载一个外部html文件并将其中的内容加以串化,但似乎无法这样做,而不会产生不希望的结果。有没有办法做到这一点?

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

但我需要加载的是实际的div内容,例如:

But what I need it to load is the actual div contents, ex:

//log: '<div id ='mydiv'>...</div>

我做错了什么?

推荐答案

function buildAd(file){
    xhr.open("GET", file);
    xhr.responseType = "DOMString";
    xhr.send();
}

这篇关于有没有办法让JSON.stringify一个HTML DOM对象? [JavaScript的]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆