这里给大家介绍两种方式,推荐使用第二种。
第一种:使用基于jquery.MyQRCode.js插件,此二维码是基于https://chart.googleapis.com/chart?chs={size}&cht=qr&chl={content}&choe={encoding} 这个网址生成的,只是沟通js封装,依赖性很强。
<html>
<head>
<title>生成二维码</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery.MyQRCode.js"></script>
<script type="text/javascript">
jQuery(function () {
jQuery("#qrCodeDiv").MyQRCode(
{
content: "设置二维码的内容。",
size: "400x400"
});
});
</script>
</head>
<body>
<div id="qrCodeDiv">
</div>
</body>
</html>
第二种,基于jquery.qrcode.min.js插件生成,这种方式方便快捷效率高,qrcode其实是通过使用jQuery实现图形渲染,画图,支持canvas(HTML5)和table两种方式,可以到https://github.com/jeromeetienne/jquery-qrcode获取最新的代码。示例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery.qrcode.min.js"></script>
<script type="text/javascript">
function generateCode() {
$("#code").qrcode({
render : "table", //table方式
width : 100, //宽度
height : 100, //高度
text : toUtf8($("#info").val())
//任意内容
});
}
</script>
</head>
<body>
This is my JSP page.
<br>
<input type="text" name="info" id="info" />
<input type="button" value="生成" onclick="generateCode()">
<div id="code"></div>
</body>
</html>
在生成内容中有中文时,会产生乱码,因为qrcode采用charCodeAt()方式进行编码转换的。而这个方法默认会获取它的Unicode编码,如果有中文内容,在生成二维码前就要把字符串转换成UTF-8,然后再生成二维码。可以通过以下函数来转换中文字符串:
//中文处理函数 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; }这样把代码:
text : $("#info").val()
修改为:
text : toUtf8($("#info").val())即可。