如何在JavaScript中执行与JSTL的c:url等效的工作? [英] How to perform equivalent of JSTL's c:url in JavaScript?
问题描述
我有一些JavaScript(使用jQuery)正在对相对网址进行Ajax调用.
I have some JavaScript that is making an Ajax call to a relative url (using jQuery).
var servletUrl = "someservlet";
$.ajax({
type: "POST",
url: servletUrl,
success: function(response) {
// ...
}
});
"someservlet"
所在的位置:
@WebServlet("/someservlet")
public class SomeServlet extends HttpServlet
我在多个页面中使用了相同的脚本.当从servlet上下文根目录中的页面使用时,则相对URL相对于servlet上下文根目录进行解析,这是正确的.当从子文件夹中的页面使用URL时,URL相对于子文件夹进行解析,这将返回404错误.
I use this same script in multiple pages. When used from a page that is in the servlet context root, then the relative url resolves relative to the servlet context root, which is correct. When used from a page that is in a subfolder the URL resolves relative to the subfolder, which will return 404 error.
我希望能够重用此JavaScript,而不必根据其中使用的页面类型对其进行修改.理想情况下,我需要与JSTL的<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 JSTL's <c:url>
tag. Is there anything in JavaScript that allows me to create URLs relative to the servlet context root?
推荐答案
几个选项:
Set a HTML
<base>
element with that value (note: has its own advantages and disadvantages)
<head>
<base href="${pageContext.request.contextPath}/" />
...
</head>
,然后在JS中:
var contextPath = $("base").attr("href");
var servletUrl = contextPath + "someservlet";
// ...
Or 在某处设置数据属性
Or set a data attribute somewhere
<html data-contextPath="${pageContext.request.contextPath}/">
...
</html>
,然后在JS中:
var contextPath = $("html").data("contextPath");
var servletUrl = contextPath + "someservlet";
// ...
Or 设置一个具有该值的全局JS变量(实践不佳):
Or set a global JS variable with that value (poor practice):
<head>
...
<script>var contextPath = "${pageContext.request.contextPath}/";</script>
</head>
,然后在JS中:
var servletUrl = contextPath + "someservlet";
// ...
这篇关于如何在JavaScript中执行与JSTL的c:url等效的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!