如何从数组 JSP 更新数组 Javascript

How to update an array Javascript from and array JSP

本文关键字:数组 更新 Javascript JSP      更新时间:2023-09-26

每次有 and 事件时,我都需要更新一个 javascript 数组,比如使用 JQuery 进行点击拦截。我需要来自JSP数组的新值进入数组javascript。

我知道有这样的解决方案将数组从.jsp传递到 javascript 函数。问题完全不同:链接的代码只运行一次,当我每次拦截事件时都需要更新时。

我可以理解问题出在从 Servlet 到 HTML 的转换中,似乎:一旦 Jsp 变量第一次取值,它们就变成了"静态代码",它无法更改。

你能给我一些替代方案或解决方案吗?

function update_coordinate_javascript()
{
    <%  
        for (int s: mycord.getXY()[0])  {
    %>
            xyscript.push(<% out.print(s); %>);
    <%
        }   
    %>
}
$("#myB").click(function(){
     $.ajax({
               type: "POST",
                url: "readXY.jsp",  // Some elaborations
                data: {incrementa:true},
                dataType: "html",
                success: function(msg)
                {
                  alert("Ok");
                },
                error: function()
                {
                  alert("Fail");
                }
              });
            update_coordinate_javascript();
            return false;
    });
}

你不能像在update_coordinate_javascript函数中那样混合使用Javascript和JSP,因为Javascript运行客户端和JSP服务器端。

在该函数中,您要做的是打印 JSP 在服务器端运行时mycord的值。你正在将它们打印到 Javascript 函数中(查看源代码进行确认),因此你基本上打印出 Javascript 代码。 一旦你这样做了,你就有一个带有硬编码列表的Javascript函数。因此,每次调用该函数时,您都只是填充相同的硬编码列表。

相反:你在 Ajax 中调用的 JSP 应该将数组打印到响应中,可以是 JSon、XML,还是保留用作分隔符的特定字符的字符串,Javascript 应该解析它。

 $.ajax({
           type: "POST",
            url: "readXY.jsp", //print array as JSON, XML, or CSV-like text there
            data: {incrementa:true},
            dataType: "html", //change this to JSON, XML, or text as needed
            success: function(msg)
            {
               //msg here is the response from the JSP you are calling, 
               //so whatever you print to response there 
               //is in this variable
               alert("Ok");
               update_coordinate_javascript(msg); //parse the msg in there
            },
            error: function()
            {
              alert("Fail");
            }
          });

那么显然,您需要从update_coordinate_javascript中删除JSP scriplet代码,并将其更改为解析传入的msg参数的Javascript代码。 你将如何做到这一点将取决于你决定如何格式化你在Ajax中调用的JSP的输出(即你是否让它返回类似CSV的文本,XML,HTML或JSON)。

因此,如果您使用 CSV,它可以像以下一样简单:

function update_coordinate_javascript(msg)
{
    var mycords = msg.split(",");
    for(var i=0; i<mycords.length; i++)
    {
       xyscript.push(mycords[i]);
    }
}