本文講述如何使用 jquery-qrcode 生成二維碼
<!-- 引入 jQuery 與 jquery.qrcode-->
<script type="text/javascript" src="jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="jquery.qrcode.min.js"></script>
<!-- 創(chuàng)建二維碼父級元素 -->
<div id="qrcode"></div>
<div id="qrcode2"></div>
<script type="text/javascript">
// 選中要生成二維碼的元素節(jié)點, 調(diào)用 qrcode 方法, 傳入數(shù)據(jù)即可
$("#qrcode").qrcode("https://google.com");
//qrcode 同時提供更多參數(shù), 具體如下
//render 繪制方式 canvas(繪制成一張圖片) table(繪制成一個表格) 默認(rèn) canvas
//width 二維碼寬度 默認(rèn) 256
//height 二維碼高度 默認(rèn) 256
//correctLevel 容錯等級 1(L),0(M),3(Q),2(H) 1 最低, 2 最高 默認(rèn)為 2
//background 背景顏色 默認(rèn)白色 #ffffff
//foreground 前景顏色 默認(rèn)黑色 #000000
// 使用示例
$("#qrcode2").qrcode({
text: "https://google.com",
render: "table",
width: 300,
height: 300,
correctLevel: 3,
background: "#eceadb",
foreground: "#444"
})
</script>
由于 qrcode 的編碼原因會導(dǎo)致中文亂碼
如果能確保二維碼中的內(nèi)容為 ** 鏈接 **, 那么在使用前對內(nèi)容進(jìn)行 encodeURI 編碼即可
$("#qrcode").qrcode(encodeURI("https://google.com"));
如果不是鏈接, 需要對二維碼內(nèi)容進(jìn)行編碼, 方法來源于 http://justcoding.iteye.com/blog/2213034
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;
}
$("#qrcode").qrcode(toUtf8("https://google.com"));
Java 生成二維碼可參考 生成二維碼之 Java(Google zxing) 篇