转自:http://suflow.iteye.com/blog/1687396
一、使用jquery-qrcode生成二维码
先简单说一下jquery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcode 获取),
qrcode.js 是实现二维码数据计算的核心类,
jquery.qrcode.js 是把它用jquery方式封装起来的,用它来实现图形渲染,其实就是画图(支持canvas和table两种方式)
 
支持的功能主要有:
 
- text     : "https://github.com/jeromeetienne/jquery-qrcode"  //设置二维码内容  
 
 
- render   : "canvas",
- width       : 256,     
- height      : 256,     
- typeNumber  : -1,      
- correctLevel    : QRErrorCorrectLevel.H,
- background      : "#ffffff",
- foreground      : "#000000" 
 
 
使用方式非常简单
 
- jQuery(‘#output‘).qrcode({width:200,height:200,correctLevel:0,text:content});  
 
 
 经过简单实践,
 
使用canvas方式渲染性能还是非常不错的,但是如果用table方式,性能不太理想,特别是IE9以下的浏览器,所以需要自行优化一下渲染table的方式,这里就不细述了。
 
二、JS生成中文二维码
其实上面的js有一个小小的缺点,就是默认不支持中文。
这跟js的机制有关系,jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,
而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,
英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。
解决方式当然是,在二维码编码前把字符串转换成UTF-8,具体代码如下:
 
- 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;  
- }  
 
 
jquery-qrcode生成二维码
原文:http://www.cnblogs.com/amw863/p/4886983.html