json html的安全方式?

ale*_*no2 3 html javascript json

我的问题很简单,我想用json重新创建一个html页面,但我不想搞乱现有的html,框架和co ...

示例:

var myDiv = { tag : "div", style : "color:blue", class : "jj", content : "Hello"};
Run Code Online (Sandbox Code Playgroud)

var myDiv = { tag : "div", style : "color:blue", class : "jj", content : "Hello"};
var param = { forbid : { tag : true, content : true } };
var createTag = function(o) {

    var node = document.createElement(o.tag);
    for (att in o) {
      if (!param.forbid[att]) node.setAttribute(att, o[att]);
    }
    node.appendChild(document.createTextNode(o.content))
    return node;

}


document.body.textContent = createTag(myDiv).outerHTML;
Run Code Online (Sandbox Code Playgroud)

这段代码的结果是:

<div style="color:blue" class="jj"> Hello </div>
Run Code Online (Sandbox Code Playgroud)

我怎样才能确定"标签"和"内容"不会混淆现有/未来的属性?保持简单?

Ori*_*iol 9

为避免与属性冲突,我会将它们分开

var myDiv = {
  tagName: "div",
  attributes: {
    style: "color: blue",
    class: "jj"
  },
  childNodes: ["Hello"]
};
Run Code Online (Sandbox Code Playgroud)

function parseTree(node) {
  if(typeof node === 'string') // Text node
    return document.createTextNode(node);
  // Otherwise, assuming an element. Consider adding
  // `node.nodeType` if you want multiple node types
  var el = document.createElement(node.tagName);
  if(node.hasOwnProperty('attributes'))
    for(var attr in node.attributes)
      if(node.attributes.hasOwnProperty(attr))
        el.setAttribute(attr, node.attributes[attr]);
  if(node.hasOwnProperty('childNodes'))
    node.childNodes.forEach(function(child) {
      el.appendChild(parseTree(child));
    });
  return el;
}
document.body.textContent = parseTree({
  tagName: "div",
  attributes: {
    style: "color: blue",
    class: "jj"
  },
  childNodes: ["Hello"]
}).outerHTML;
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用包含属性名称中不允许的某些字符的字符串.例如,\u0000\u0000Run Code Online (Sandbox Code Playgroud)

  • @ alexino2如果你想允许任意属性,这是0only选项. (2认同)

归档时间:

查看次数:

78 次

最近记录:

9 年,11 月 前