【问题标题】:Pass Parameter to Querystring AND Fire Javascript Function将参数传递给查询字符串并触发 Javascript 函数
【发布时间】:2012-01-05 09:23:11
【问题描述】:

我有一个搜索功能,可以将对象数组列表返回到我的表单。我正在使用 JSTL 的 foreach 标记遍历列表。

<c:forEach items="${searchResults}" var="contact" varStatus="loop">
<div style="padding: 5px;">
${contact.firstName} ${contact.lastName}
<br>
${contact.primaryPhone}
<br>

//Is this the proper way to set up the url?
<a href="Contacts?search=${param.search}&id=${loop.index}">View Contact</a>

</div>
<br>
</c:forEach>

当用户单击每一行内的链接时,行索引将传递给查询字符串,此时我想显示一个包含有关用户的其他信息的 div。

我有一个 javascript 函数,用于显示 div 并将其居中在屏幕上 bla bla bla,但我的问题是如何刷新页面并将索引加载到查询字符串中,然后触发我的 javascript 函数?

我考虑过使用:

<c:if test="${not empty param.id}">
//Check if id in querystring is available and if so, display popup
</c:if>

检查查询字符串中是否有可用的索引,但我认为没有办法从 JSTL 标记中触发我的函数。

当我向 servlet 请求返回时,我是否应该在服务器端做一些事情,而不是尝试在客户端处理它?我只是认为重新查询我的数据库并设置另一个请求参数是一种浪费,当我已经将所需的信息存储在一个参数中而不是用来显示我的列表时。

【问题讨论】:

    标签: javascript jsp jakarta-ee servlets jstl


    【解决方案1】:

    我最终想出的解决方案是每次页面加载时检查查询字符串中的 id 参数(使用 javascript)

    function init(){
    console.log("Contacts page loaded.");
    
    //Loads popup if 'id' is present in the querystring.
    if(getQuerystring('id', 'null') !== 'null') {
        showCenteredDiv('popup');
    }
    };
    

    我用来检查查询字符串的函数是:

    //Search querystring for a specific parameter. Second arg is the value to display if its not found.
    function getQuerystring(key, default_)
    {
      if (default_==null) default_="";
    
      key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var qs = regex.exec(window.location.href);
    
      if(qs == null) {
        return default_;
      } else {
        return qs[1];
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以在参数检查中嵌入脚本标签,并在其中运行您想要的任何内容。例如,设置一些变量,您可以稍后在页面完成加载时进行测试。 或者,如果您在页面中嵌入参数检查的时间足够晚,只需调用您的函数。

      <c:if test="${not empty param.id}"> 
          <script>
              runSomeFunction();
          </script>
      </c:if>
      

      【讨论】:

      • 这确实有效,但为了保持更干净的 html 并将所有 javascript 保存在外部文件中,我想出了另一个解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2014-11-02
      • 1970-01-01
      • 2020-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多