admin管理员组文章数量:1287525
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) {
// ...
}
});
Where "someservlet"
is:
@WebServlet("/someservlet")
public class SomeServlet extends HttpServlet
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.
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?
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) {
// ...
}
});
Where "someservlet"
is:
@WebServlet("/someservlet")
public class SomeServlet extends HttpServlet
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.
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?
1 Answer
Reset to default 11Several options:
Set a HTML
<base>
element with that value (note: has its own advantages and disadvantages)<head> <base href="${pageContext.request.contextPath}/" /> ... </head>
and then in JS:
var contextPath = $("base").attr("href"); var servletUrl = contextPath + "someservlet"; // ...
Or set a data attribute somewhere
<html data-contextPath="${pageContext.request.contextPath}/"> ... </html>
and then in JS:
var contextPath = $("html").data("contextPath"); var servletUrl = contextPath + "someservlet"; // ...
Or set a global JS variable with that value (poor practice):
<head> ... <script>var contextPath = "${pageContext.request.contextPath}/";</script> </head>
and then in JS:
var servletUrl = contextPath + "someservlet"; // ...
本文标签: jqueryHow to perform equivalent of JSTL39s curl in JavaScriptStack Overflow
版权声明:本文标题:jquery - How to perform equivalent of JSTL's c:url in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741312521a2371728.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论