将条件spring mvc参数传递到javascript url函数

将条件spring mvc参数传递到javascript url函数,java,javascript,spring,spring-mvc,Java,Javascript,Spring,Spring Mvc,我在SpringMVC应用程序中有一个javascript日历控件。当用户单击日历控件中的日期时,用户将重定向到该日期的详细信息页面。问题是,除了日期之外,我还想在url中传递其他参数。如何在javascript功能中向url添加其他参数 以下是用于创建url的javascript,该url仅包含日期作为参数: <script type="text/javascript"> $(document).ready(function(

我在SpringMVC应用程序中有一个javascript日历控件。当用户单击日历控件中的日期时,用户将重定向到该日期的详细信息页面。问题是,除了
日期
之外,我还想在url中传递其他参数。如何在javascript功能中向url添加其他参数

以下是用于创建url的javascript,该url仅包含
日期
作为参数:

        <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>  

如何更改上面的javascript,使其添加
pid
eid
的参数,当且仅当
pid
eid
非空时

这可以通过连接由
&
字符分隔的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;
此外,如果您没有在模型为“null”时实际添加eid或pid,那么它实际上不会为null,因此您也可能无法获得所需的功能。如果您实际将eid和pid添加到模型中作为“null”,那么上面的内容应该可以。但是,如果eid和pid为null,您只需将它们一起排除在模型之外,则需要进行如下检查:

var url=“${pageContext.request.contextPath}/calendar?day=“+encodeURIComponent(dateText);
if(${!空pid}){
url+=“&pid=“+encodeURIComponent(${pid});
}
if(${!空eid}){
url+=“&eid=“+encodeURIComponent(${eid});
}
window.location=url;

+1谢谢。但是您的代码正在url的末尾添加一个
符号,因此看起来是这样的:
/calendar?day=2014-03-10&pid=1
。有没有办法修改你的代码,使它不会在最后留下一个
#
符号?我很高兴能提供帮助,
#
是书签符号,可以安全地忽略它,因为它不会在POST/get时发送到服务器。不知何故,encodeURIComponent似乎正在添加itI am测试代码,结果是以下两行导致链接从未更改日期参数的值:
if(pid){url+=”&pid=“+encodeURIComponent(pid);}
if(eid){url+=”&eid=“+encodeURIComponent(eid);}
。当我删除这两行时,您建议的其余代码允许我更改日期,但是
eid
pid
参数不会添加到url中。如何解决此问题?我的帖子中的代码设置了用户在jquery datepicker工具中的日历日单击此链接时的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;