如何将数据安全地放入div标记?

时间:2021-10-05 20:28:17

I used ajax to download a JSON file from the internet, then set one of the keys to a variable. How do I get the contents of that variable inside a div tag? I could do:

我使用ajax从internet下载JSON文件,然后将其中一个键设置为变量。如何在div标签中获取该变量的内容?我能做的:

theJsonKey = jsonObject.key;  
document.getElementById('theDivTag').innerHTML = theJsonKey;

But that doesn't seem safe since someone could put scripts or html in the JSON file.

但这似乎并不安全,因为有人可以将脚本或html放入JSON文件中。

2 个解决方案

#1


2  

The safest/most cross-browser way might be to do this. createTextNodeinnerHTML

最安全/最跨浏览器的方法可能是这样做。createTextNode innerHTML

document.getElementById('theDivTag').innerHTML = "";
document.getElementById('theDivTag').appendChild(document.createTextNode(theJsonKey));

Credit to Matt McDonald for appendChild :P

感谢马特·麦克唐纳为appendChild:P

(I should have seen that one)

(我应该看到那个)

#2


1  

What happens behind the scenes for HTML Encoding.

HTML编码的幕后发生的事情。

function safeHtml(v) {
    return v.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g, '&apos;');
}

& ==> &amp;

& = = >,

> ==> &gt;

> = = >比;

< ==> &lt;

< = = > & lt;

" ==> &quot;

”= = >“

' ==> &apos;

事情就让它' = = >,

For a more complete list for character entities for HTML http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

关于HTML http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references的更完整的字符实体列表

#1


2  

The safest/most cross-browser way might be to do this. createTextNodeinnerHTML

最安全/最跨浏览器的方法可能是这样做。createTextNode innerHTML

document.getElementById('theDivTag').innerHTML = "";
document.getElementById('theDivTag').appendChild(document.createTextNode(theJsonKey));

Credit to Matt McDonald for appendChild :P

感谢马特·麦克唐纳为appendChild:P

(I should have seen that one)

(我应该看到那个)

#2


1  

What happens behind the scenes for HTML Encoding.

HTML编码的幕后发生的事情。

function safeHtml(v) {
    return v.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g, '&apos;');
}

& ==> &amp;

& = = >,

> ==> &gt;

> = = >比;

< ==> &lt;

< = = > & lt;

" ==> &quot;

”= = >“

' ==> &apos;

事情就让它' = = >,

For a more complete list for character entities for HTML http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

关于HTML http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references的更完整的字符实体列表