HTML的元素嵌入data,如何解码数据

在html中,往往会直接嵌入数据到元素的属性中,在使用的时候直接将这些属性解析成对应的数据类型,供后面使用。例如:

<table class="xxxx" id="123" data-toggle="datagrid" data-url="{{$.BaseUrl}}{{$index}}" data-options={{MapToStr .Option}} data-width="100%" class="table table-bordered"></table>
//在需要用的地方[一般在组件中使用],获取相关属性
<script type="text/javascript">
    var option=$("#123").data()
    //假设url参数可以是string,也可以是一个数组
    var urlPara=option.url;
    try{
        urlPara=JSON.parse(option.url)  //容易报错
    }catch(e){
        console.log(option.url+"----err----"+e)
    }
    if(urlPara instanceof Array){
           //按数组处理 
    }else{pre
          //按string处理
    }
</script>>

问题:
当嵌入的数据为数组类型的时候,如"[%22http://www.w3school.com.cn/My%20first/%22%20%22%http://www.w3school.com.cn/My first/"]"这样解析就会报错,报错内容为:

    bjui-all.js:20776 error:!!!SyntaxError: Unexpected token % in JSON at position 1

原因:
因为这个字符串中含有html编码“%22”等,导致解析错误;所以只需要将这些字符解码,然后再重新解析,即可得到正确的数据结构了
方案:
使用umescapse,decodeURI,decodeURIComponent等函数解码,在解析字符串到正确的数据结构。

	urlPara=JSON.parse(decodeURI(option.url))   

相关知识点回顾
1、知识链接

2、快速回顾

函数 描述
decodeURI() 解码某个编码的 URI。
decodeURIComponent() 解码一个编码的 URI 组件。
encodeURI() 把字符串编码为 URI。
encodeURIComponent() 把字符串编码为 URI 组件。
escape() 对字符串进行编码。
eval() 计算 JavaScript 字符串,并把它作为脚本代码来执行。
getClass() 返回一个 JavaObject 的 JavaClass。
isFinite() 检查某个值是否为有穷大的数。
isNaN() 检查某个值是否是数字。
Number() 把对象的值转换为数字。
parseFloat() 解析一个字符串并返回一个浮点数。
parseInt() 解析一个字符串并返回一个整数。
String() 把对象的值转换为字符串。
unescape() 对由 escape 编码的字符串进行解码

3、拓展:字符串转换成其他数据结构
参考BJUI框架的代码,将字符串转换成其他数据类型,转换成对象:

    toObj: function() {
            var obj = null
            
            try {
                obj = (new Function('return '+ this))()
            } catch (e) {
                obj = this
                BJUI.debug('String toObj:Parse "String" to "Object" error! Your str is: '+ this)
            }
            return obj
        }
原文地址:https://www.cnblogs.com/meiguhuaxian/p/14140867.html