将有条件的spring MVC参数传入javascript url函数

passing conditional spring mvc parameters into javascript url function

本文关键字:javascript url 函数 参数 有条件 spring MVC      更新时间:2023-09-26

我在一个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的其他地方生成包含另外两个可选参数(pideid)的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,使它为pideid添加参数当且仅当 pideidnot 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;