1

您好,我正在使用此 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>

谢谢 ...

4

2 回答 2

3

您必须使用正确的引号来传递字符串:

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" />

该字段将可以通过它的“值”属性在客户端和服务器端访问。

于 2012-06-15T13:24:24.893 回答
1
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 
于 2012-06-15T12:52:36.707 回答