将参数传递给Querystring和Fire Javascript函数

时间:2011-11-24 06:47:40

标签: javascript jsp java-ee servlets jstl

我有一个搜索功能,可以将对象的arraylist返回给我的表单。我正在使用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函数?< / p>

我考虑过使用:

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

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

当我请求回servlet而不是尝试在客户端处理这个问题时,我是否应该在服务器端做某事?我只是觉得浪费重新查询我的数据库并设置另一个请求参数,当我已经有一个参数存储在一个参数中,而不是用来显示我的列表。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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];
  }
}
相关问题