将变量从 VB 函数传递到客户端 JavaScript
本文关键字:客户端 JavaScript 函数 变量 VB | 更新日期: 2023-09-27 18:37:14
你好,我正在使用这个Page.ClientScript.RegisterStartupScript()从vb代码后面调用javascript函数,这对我来说很好用 我的问题是如何将变量从后面的代码发送到javascript函数,这是我到目前为止尝试过的:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.LoadComplete
Dim Myname As String = "myName"
Dim cstype As Type = Me.GetType()
Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello(Myname);",
True)
End Sub
JavaScript :
<script type="text/javascript">
function hello(name) {
alert("hello world from javascript " + name)
}
</script>
谢谢。。。
您必须使用正确的引号来传递字符串:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.LoadComplete
Dim Myname As String = "myName"
Dim cstype As Type = Me.GetType()
Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('" & Myname & "');",
True)
End Sub
请注意变量名称两边的单引号。
在客户端和服务器端代码之间双向传递数据的另一种方法是隐藏字段,例如
<asp:HiddenField ID="xhidMyname" runat="server" />
或
<input type="hidden" id="xhidMyname" runat="server" />
此字段可通过其"value"属性在客户端和服务器端访问。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.LoadComplete
Dim Myname As String = "myName"
Dim cstype As Type = Me.GetType()
Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('"&Myname&"');",
True)
End Sub