您如何以正确的方式从 JavaScript 获取 contextPath?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6615641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get the contextPath from JavaScript, the right way?
提问by Mike M. Lin
Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why? I can think of a few possibilities. Am I missing any?
使用基于 Java 的后端(即 servlet 和 JSP),如果我需要来自 JavaScript 的 contextPath,那么推荐的模式是什么,为什么?我能想到几个可能性。我缺什么吗?
1. Burn a SCRIPT tag into the page that sets it in some JavaScript variable
1. 将 SCRIPT 标签刻录到页面中,并在一些 JavaScript 变量中设置它
<script>var ctx = "<%=request.getContextPath()%>"</script>
This is accurate, but requires script execution when loading the page.
这是准确的,但需要在加载页面时执行脚本。
2. Set the contextPath in some hidden DOM element
2.在一些隐藏的DOM元素中设置contextPath
<span id="ctx" style="display:none;"><%=request.getContextPath()%></span>
This is accurate, and doesn't require any script execution when loading the page. But you do need a DOM query when need to access the contextPath. The result of the DOM query can be cached if you care that much about performance.
这是准确的,并且在加载页面时不需要执行任何脚本。但是当需要访问 contextPath 时,您确实需要一个 DOM 查询。如果您非常关心性能,则可以缓存 DOM 查询的结果。
3. Try to figure it out within JavaScript by examining document.URL
or the BASE tag
3. 尝试通过检查document.URL
或 BASE 标签在 JavaScript 中找出它
function() {
var base = document.getElementsByTagName('base')[0];
if (base && base.href && (base.href.length > 0)) {
base = base.href;
} else {
base = document.URL;
}
return base.substr(0,
base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));
};
This doesn't require any script execution when loading the page, and you can also cache the result if necessary. But this only works if you know your context path is a single directory -- as opposed to the root directory (/
) or the multiple directories down (/mypath/iscomplicated/
).
这在加载页面时不需要任何脚本执行,如果需要,您还可以缓存结果。但这仅在您知道上下文路径是单个目录时才有效——而不是根目录 ( /
) 或向下的多个目录 ( /mypath/iscomplicated/
)。
Which way I'm leaning
我靠哪边
I'm favoring the hidden DOM element, because it doesn't require JavaScript code execution at the load of the page. Only when I need the contextPath, will I need to execute anything (in this case, run a DOM query).
我喜欢隐藏的 DOM 元素,因为它不需要在页面加载时执行 JavaScript 代码。仅当我需要 contextPath 时,才需要执行任何操作(在本例中,运行 DOM 查询)。
回答by Mike M. Lin
Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:
根据评论中的讨论(特别是来自 BalusC),可能不值得做比这更复杂的事情:
<script>var ctx = "${pageContext.request.contextPath}"</script>
回答by Cedric Simon
Got it :D
明白了:D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.
重要说明:仅适用于“根”上下文路径。不适用于“子文件夹”,或者上下文路径中是否有斜线(“/”)。
回答by Cedric Simon
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
我认为您可以通过将数字 1 与调用类似数字 3 的函数相结合来实现您想要的。
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
您不想在页面加载时执行脚本并希望稍后调用函数?很好,只需创建一个函数来返回您在变量中设置的值:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
这是一个函数,因此在您实际调用它之前不会执行它,但它直接返回值,无需进行 DOM 遍历或修改 URL。
At this point I agree with @BalusC to use EL:
在这一点上,我同意@BalusC 使用 EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
或根据 JSP 回退到 JSTL 的版本:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
回答by Oleg Shavrov
I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:
我使用 id="contextPahtHolder" 将上下文路径渲染到链接标签的属性,然后在 JS 代码中获取它。例如:
<html>
<head>
<link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
main.js
主文件
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});
If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string
如果上下文路径为空(如在嵌入式 servlet 容器实例中),它将是空字符串。否则它包含 contextPath 字符串
回答by Armando Cordova
Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:
Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:
Javascript:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
回答by Michael Hegner
A Spring Boot with Thymeleaf solution could look like:
带有 Thymeleaf 解决方案的 Spring Boot 可能如下所示:
Lets say my context-path is /app/
假设我的上下文路径是 /app/
In Thymeleaf you can get it via:
在 Thymeleaf 中,您可以通过以下方式获得它:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[@{/}]]*/
/*]]>*/
</script>