问题描述
我有一些javascript正在对相对url进行ajax调用(使用JQuery)。我在多个页面中使用相同的脚本。当从作为Spring WebFlow执行的一部分的页面使用时,相对url相对于servlet上下文根解析。当从不属于WebFlow执行的页面使用时,URL会相对于当前页面进行解析。
I have some javascript that is making an ajax call to a relative url (using JQuery). I use this same script in multiple pages. When used from a page that is part of a Spring WebFlow execution the relative url resolves relative to the servlet context root. When used from a page that is not part of a WebFlow execution the URL resolves relative to the current page.
我希望能够重用此javascript而不必根据其中使用的页面类型进行修改。理想情况下,我需要等效的JSP c:url标记。 Javascript中有什么允许我创建相对于servlet上下文根的URL吗?
I would like to be able to reuse this javascript without having to modify it depending on the type of page that it is used within. Ideally, I need the equivalent of the JSP c:url tag. Is there anything in Javascript that allows me to create URLs relative to the servlet context root?
这是我的javascript的精简版。
This is a trimmed down version of my javascript.
$.getJSON(
"ref_data/country_options",
{id: countryId},
function(countryOptions) {
// ... do stuff
}
};
推荐答案
使用该值设置HTML < base>
元素(注意:有自己的)
Either set a HTML <base>
element with that value (note: has its own advantages and disadvantages)
<c:set var="req" value="${pageContext.request}" />
...
<head>
<base href="${fn:replace(req.requestURL, fn:substring(req.requestURI, 1, fn:length(req.requestURI)), req.contextPath)}" />
...
</head>
一个d然后在JS中:
var base = document.getElementsByTagName('base')[0].href;
// ...
或设置全局JS具有该值的变量:
Or set a global JS variable with that value:
<c:set var="req" value="${pageContext.request}" />
...
<head>
...
<script>var base = '${fn:replace(req.requestURL, fn:substring(req.requestURI, 1, fn:length(req.requestURI)), req.contextPath)}';</script>
</head>
然后它将在你的JS函数中提供。
and then it'll be available as such in your JS function.
这篇关于如何在javascript中执行JSP的c:url等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!