1、jquery.qrcode.js介绍javascript
jquery.qrcode.js 是一个纯浏览器 生成 QRcode 的 jQuery 插件((能够从https://github.com/jeromeetienne/jquery-qrcode 获取)),它使用很是简单,生成的 QRcode 无需下载图片,而且不依赖第三方服务,插件压缩以后大小小于 4K。java
2、参数说明jquery
3、jquery.qrcode使用
git
1. 加载 jQuery 和 jquery.qrcode.js:github
<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script> canvas
<script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script> 浏览器
2. 建立一个用于包含 QRcode 图片的 DOM 元素,好比 div:微信
<div id="qrcode"></div> 编码
3.经过下面代码生成 QRcode:spa
最简单方式:jQuery('#qrcode').qrcode("http://blog.csdn.net/mr_smile2014");
自定义方式:jQuery('#qrcode').qrcode({render:canvas,width: 64,height: 64,correctLevel:0,text: "http://blog.csdn.net/mr_smile2014"});
4、常见问题
1.在chorme浏览器中二维码生成成功后没法扫描解决方法:
//改为使用table的渲染方式,亲测支持各类各版本的浏览器
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,render: "table",text: "http://blog.csdn.net/mr_smile2014"});
2.在微信或手机浏览器中生成的二维码没法扫描解决方法;
//改为使用默认的渲染方式,支持微信和QQ内置浏览器及其它手机浏览器
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: "http://blog.csdn.net/mr_smile2014"});
jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,这个方法默认会获取它的 Unicode 编码,通常的解码器都是采用UTF-8, ISO-8859-1等方式。
英文是没有问题,若是是中文,通常状况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。
解决方式固然是,在二维码编码前把字符串转换成UTF-8,具体代码以下:
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: utf16to8("jquery-qrcode竟然不支持中文,太可恨了!")});
function utf16to8(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;
}
3.jquery.qrcode生成二维码内容不支持中文