解決jquery.qrcode中文識別問題

用法

<script src="//cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
$('#容器ID').qrcode("文字"); //任意字符串

識別中文

咱們試驗的時候發現不能識別中文內容的二維碼,經過查找多方資料瞭解到,jquery-qrcode是採用charCodeAt()方式進行編碼轉換的。而這個方法默認會獲取它的Unicode編碼,若是有中文內容,在生成二維碼前就要把字符串轉換成UTF-8,而後再生成二維碼。您能夠經過如下函數來轉換中文字符串:css

function toUtf8(str) {    
    var out, i, len, c;    
    out = "";    
    len = str.length;    
    for(i = 0; i < len; i++) {    
        c = str.charCodeAt(i);    
        if ((c >= 0x0001) && (c <= 0x007F)) {    
            out += str.charAt(i);    
        } else if (c > 0x07FF) {    
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));    
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));    
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
        } else {    
            out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));    
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
        }    
    }    
    return out;    
}

如下示例:jquery

var str = toUtf8("釣魚島是中國的!"); 
$('#code').qrcode(str);
相關文章
相關標籤/搜索