使用jquery.qrcode生成二維碼
來源:程序員人生 發布時間:2015-03-31 08:37:29 閱讀次數:3910次
1、首先在頁面中加入jquery庫文件和qrcode插件。
<script type="text/javascript" src="
jquery.js"></script>
<script type="text/javascript" src="
jquery.qrcode.min.js"></script>
2、在頁面中需要顯示2維碼的地方加入以下代碼:
<div id="code"></div>
3、調用qrcode插件。
qrcode支持canvas和table兩種方式進行圖片渲染,默許使用canvas方式,效力最高,固然要閱讀器支持html5。直接調用以下:
$('#code').qrcode("http://www.codesky.net"); //任意字符串
您也能夠通過以下方式調用:
$("#code").qrcode({
render: "table", //table方式
width: 200, //寬度
height:200, //高度
text: "www.codesky.net" //任意內容
});
這樣就能夠在頁面中直接生成1個2維碼,你可以用手機“掃1掃”功能讀取2維碼信息。
辨認中文
我們實驗的時候發現不能辨認中文內容的2維碼,通過查找多方資料了解到,jquery-qrcode是采取charCodeAt()方式進行編碼轉換的。而這個方法默許會獲得它的Unicode編碼,如果有中文內容,在生成2維碼前就要把字符串轉換成UTF⑻,然后再生成2維碼。您可以通過以下函數來轉換中文字符串:
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);

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈