编码 url html javascript

url编码:

对url的编码,因为/ : '  空格等特殊符号包含在url中会影响url的正常解析,需要对这些特殊字符编码,取值时再解码得到对应的值

http://www.baidu.com 被编码后就是http%3a%2f%2fwww.baidu.com,其中的/和:被编码

post get的表单内容都会被浏览器先编码然后提交

html编码:

和url一样html中也有特殊字符,如< ' ",想让这些字符在html中正常显示也需要对其编码,解码会由浏览器自动执行

如想在一个div中显示<,应该是<div>&lt;</div>,被浏览器解码后会变成<div><</div>,直接使用这个代码可能会导致html解码错误(<会使html解析器认为这是标签,去寻找对应的>但是却没有,这只是为了显示<字符)

javascript编码:

和html编码基本一样,只是编码类型不一样,它会将字符编码成\x3c类型,只要使用javascript进行字符相关操作,javascript就会自动将字符串先解码,如在javascript中动态给dom赋值的话要注意这个问题(会存在XSS漏洞)

如<div id="contentDiv">\x3c</div>如果直接写在html中,这不会有问题,浏览器中就是显示\x3c

但是如果使用javascript赋值:document.getElementById("contentDiv").innerHTML="\x3cscript\x3ealert(\x27pwnd\x27);\x3c/script\x3e",解码后是<script>alert('pwnd');</script>,就存在了安全隐患,一些要通过javascript进行DOM赋值的字符变量需要在服务端先进行javascript编码,以防止恶意输入导致XSS漏洞

这个编码功能javascript自带的API没有,也就是说想实现在一个text的input输入字符串,然后通过javascript在另一个div中显示是不能直接做到的(输入标签的标签等特殊符号不会显示)

不过可以自己用javascript写2个辅助函数实现html的编码和解码功能

       function HtmlEncode(str) {
           var s = "";
           if (str.length == 0)
               return "";
           s = str.replace(/&/g, "&gt;");
           s = s.replace(/</g, "&lt;");
           s = s.replace(/>/g, "&gt;");
           s = s.replace(/\"/g, "&quot;");
           s = s.replace(/\n/g, "<br>");
           return s;
       }
       function HtmlDecode(str) {
           var s = "";
           if (str.length == 0) return "";
           s = str.replace(/&gt;/g, "&");
           s = s.replace(/&lt;/g, "<");
           s = s.replace(/&gt;/g, ">");
           s = s.replace(/&nbsp;/g, " ");
           s = s.replace(/"/g, "\"");
           s = s.replace(/&quot;/g, "\"");
           s = s.replace(/<br>/g, "\n");
           return s;
       }
       //调用示例
       document.getElementById("Button1").onclick = function () {

           document.getElementById("contentDiv").innerHTML = HtmlEncode(document.getElementById("Text1").value);
       }

           

原文地址:https://www.cnblogs.com/FlyCat/p/2616029.html