直接进入正题:
引入jquery js 和jquery-qrcode.js ,稍后本人会将代码demo上传至资源库。代码很简单:
如果是非中文的字符生成二维码,那么就比较简单了。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.qrcode.min.js"></script> <script> $(function() { $("#qrcode").qrcode("welcome to China"); }); </script> <body> <div id="qrcode"></div> </body> </html>如果是中文字符或者含有中文字符,那么就需要做一些编码转换,将UTF-16转换为UTF-8
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.qrcode.min.js"></script> <script type="text/javascript" src="js/convertCN.js"></script> <script> $(function() { $("#qrcode").qrcode(utf16to8("黄斌")); }); </script> <body> <div id="qrcode"></div> </body> </html>
convertCN.js的内容如下:
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; }
其中第三个js的引入是自定义的,用来解决中文无法识别的问题。jquery相对于Java servlet 生成二维码来说,更加快捷,方便,依赖更少的插件。
原文地址:http://blog.csdn.net/michael10001/article/details/39289343