我正在使用JsBarcode
我正在尝试显示从文本框的值生成的条形码图像。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JsBarcode.all.js"></script>
<script>
function textToBase64Barcode(text) {
var canvas = document.createElement("canvas");
JsBarcode(canvas, text, { format: "CODE39" });
return canvas.toDataURL("image/png");
}
function getBarcode() {
var input = document.getElementById('<%= txtInput.ClientID %>').value;
document.getElementById("image").setAttribute("src", textToBase64Barcode(input));
}
</script>
</head>
<body>
<form id="form1" runat="server">
<img id="image" />
<br />
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Show Barcode" OnClientClick="getBarcode()" />
<br />
</form>
</body>
</html>
我遇到的问题是条形码会立即出现并消失。我如何:
答案 0 :(得分:0)
条形码消失,因为当单击按钮时,即使没有与按钮关联的操作,页面也会执行回发。您可以禁用该按钮,但不会在后面的代码中获得条形码的base64字符串。
所以你可以这样做:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="JsBarcode.all.js"></script>
<script type="text/javascript" >
function textToBase64Barcode(text) {
var canvas = document.createElement("canvas");
JsBarcode(canvas, text, { format: "CODE39" });
return canvas.toDataURL("image/png");
}
function getBarcode() {
var input = document.getElementById('<%= txtInput.ClientID %>').value;
document.getElementById("image").setAttribute("src", textToBase64Barcode(input));
//set the base64 value in a hiddenfield so the code-behind can process it on postback
document.getElementById('<%= HiddenField1.ClientID %>').value = textToBase64Barcode(input);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<img id="image" />
<br />
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Show Barcode" OnClientClick="getBarcode()" OnClick="btnSubmit_Click" />
<br />
<!-- hiddenfield containing the base64 value -->
<asp:HiddenField ID="HiddenField1" runat="server" />
</form>
</body>
</html>
在后面的代码中:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//you can now do something with the base64 value
string base64 = HiddenField1.Value;
//call the javascript code when the postback is done so the barcode is generated again
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "reloadBarcode", "getBarcode()", true);
}
答案 1 :(得分:0)
如果您还没有找到解决方案,则只需向return false;
添加OnClientClick
即可阻止PostBack
<asp:Button ID="btnSubmit" runat="server" Text="Show Barcode" OnClientClick="getBarcode(); return false;" />