Skip to content

解决 jquery.qrcode 中文识别问题

用法

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

识别中文

我们试验的时候发现不能识别中文内容的二维码,通过查找多方资料了解到,jquery-qrcode 是采用 charCodeAt()方式进行编码转换的。而这个方法默认会获取它的 Unicode 编码,如果有中文内容,在生成二维码前就要把字符串转换成 UTF-8,然后再生成二维码。您可以通过以下函数来转换中文字符串:

javascript
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;
}
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;
}

以下示例:

javascript
var str = toUtf8("钓鱼岛是中国的!");
$("#code").qrcode(str);
var str = toUtf8("钓鱼岛是中国的!");
$("#code").qrcode(str);

最后编辑时间:

Version 4.0 (framework-1.0.0-rc.20)