在使用jquery.qrcode.js这个插件生成二维码的时候发现并不能识别中文。
原因在于:jquery-qrcode是采用charCodeAt()方式进行编码转 换的。
而这个方法默认会获取它的Unicode编码,如果有中文内容,在生成二维码前就要把字符串转换成UTF-8,然后再生成二维码。
解决办法:
通过以下函 数来转换中文字符串:
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; ???????}
然后再使用就可以了。
var str = toUtf8("钓鱼岛是中国的!"); ??$(‘#code‘).qrcode(str);
生成二维码的 jQuery 插件:jquery.qrcode.js的中文乱码问题
原文地址:http://www.cnblogs.com/syq816/p/8025087.html