将有条件的spring MVC参数传入javascript url函数
passing conditional spring mvc parameters into javascript url function
我在一个spring mvc应用程序中有一个javascript日历控件。当用户单击日历控件中的date
时,用户将被重定向到该日期的详细页面。问题是,除了date
之外,我还想在url中传递其他参数。如何在javascript功能中向url添加其他参数?
下面是创建url的javascript,只有date
作为参数:
<script type="text/javascript">
$(document).ready(function() {
$("#dayPicker").datepicker({
firstDay: 1,
dateFormat: "yy-mm-dd",
defaultDate: new Date(${calendar.dayMillis}),
onSelect: function(dateText, instance) {
window.location = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);
}
});
});
</script>
为了便于说明,下面的代码用于在JSP的其他地方生成包含另外两个可选参数(pid
和eid
)的url:
<c:url var="previousLink" value="/calendar">
<c:param name="day" value="${calendar.previousDay}" />
<c:choose>
<c:when test="${pid!=null}">
<c:param name="pid" value="${pid}" />
</c:when>
<c:otherwise></c:otherwise>
</c:choose>
<c:choose>
<c:when test="${eid!=null}">
<c:param name="eid" value="${eid}"></c:param>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
</c:url>
<a href="${previousLink}">Previous</a>
我如何改变上面的javascript,使它为pid
和eid
添加参数当且仅当 pid
或eid
是not null
?
这可以通过连接以&
字符分隔的URL参数来完成:
var url = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);
if (pid) {
url += "&pid=" + encodeURIComponent(pid);
}
if (eid) {
url += "&eid=" + encodeURIComponent(eid);
}
window.location = url;
注意到您关于pid和eid不工作的注释,很可能您需要添加jquery括号来获取pid和eid。就像这样:
var url = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);
if (${pid!=null}) {
url += "&pid=" + encodeURIComponent(${pid});
}
if (${eid!=null}) {
url += "&eid=" + encodeURIComponent(${eid});
}
window.location = url;
另外,如果你没有实际添加eid或pid到模型时,它是'null',它实际上不会是空的,所以你可能无法得到所需的功能。如果您实际上将eid和pid添加到模型为"null",那么上述应该没问题。但是,如果eid和pid为空,您只是将它们一起从模型中删除,则需要这样检查:
var url = "${pageContext.request.contextPath}/calendar?day=" + encodeURIComponent(dateText);
if (${! empty pid}) {
url += "&pid=" + encodeURIComponent(${pid});
}
if (${! empty eid}) {
url += "&eid=" + encodeURIComponent(${eid});
}
window.location = url;
相关文章:
- Javascript url rewriter
- Javascript, url object compression
- 我们可以在javascript url中传递GET变量吗
- 所有悬停的Javascript url代码
- JavaScript URL搜索规则
- 剃刀视图中的Javascript url操作
- JavaScript: ΔURL, Refresh
- 基于变量的Javascript URL重定向无法正常工作
- 为什么JavaScript URL表单无法工作,也无法重定向
- Javascript Url 操作和后退导航
- 将变量添加到 javascript url 调用
- javascript url redirect with regex
- JavaScript URL checking for pupunder
- 带有 JavaScript URL 重定向的正则表达式
- 将锚标记添加到 JavaScript URL
- 在 Javascript URL 中传递两个变量,以根据传递的值更新下拉列表
- 设置一个 JavaScript URL
- 通过 JavaScript URL 可变快捷方式扩展 HTML URL
- Javascript url 参数解析
- JavaScript URL 未定义的重定向