【问题标题】:Trying to pass an array variable from asp to javascript试图将数组变量从 asp 传递给 javascript
【发布时间】:2022-01-07 00:04:24
【问题描述】:

试图将数组变量传递给 java 以下不工作,知道为什么以及如何使其工作

背后的代码

Public myArray (5) As String
myArray(1) = "A1"
myArray(2) = "A2"
myArray(3) = "A3"
myArray(4) = "A4"
myArray(5) = "A5"

在asp中

<button type = "button" onclick="myJava('<%= myArray %>');">Search</button>

在 Javascript 中

function myJava (myArray) {
   alert(myArray[1]); // expected answer is A1 but it is not
}

【问题讨论】:

  • “预期答案是 A1,但不是” 你看到了什么?不是一个 asp 人,但你的数组周围的单引号会导致你传递一个字符串,也许试试:onclick="myJava(&lt;%= myArray %&gt;);"
  • myArray[1] 给 y 而 myArray[2] 给 s,很奇怪
  • 我试过删除单引号,它拒绝执行 onclick
  • 嗯,alert(myArray) 显示什么?
  • System.String[]

标签: javascript html asp.net


【解决方案1】:

您需要正确编码您的数组。首先,您需要将其转换为 JSON 字符串;那么您需要将该字符串编码为 HTML 属性值。

添加对the Newtonsoft.Json NuGet package 的引用。为 Newtonsoft.Json 命名空间添加 Imports 语句。向您的代码隐藏添加一个方法以返回正确编码的函数调用:

Public Function PassArrayToJavascript(ByVal functionName As String) As String
    Dim json As String = JsonConvert.SerializeObject(myArray)
    Dim result As String = functionName + "(" + json + ");"
    Return System.Web.HttpUtility.HtmlAttributeEncode(result)
End Function

然后更新你的标记来调用这个函数:

<button type = "button" onclick="<%= PassArrayToJavascript("myFunction") %>">Search</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多