Mik*_*Lin 62 javascript jsp servlets
使用基于Java的后端(即servlet和JSP),如果我需要来自JavaScript的contextPath,建议的模式是什么,为什么?我可以想到一些可能性.我错过了吗?
1.将SCRIPT标记刻录到将其设置在某个JavaScript变量中的页面中
<script>var ctx = "<%=request.getContextPath()%>"</script>
Run Code Online (Sandbox Code Playgroud)
这是准确的,但在加载页面时需要执行脚本.
2.在一些隐藏的DOM元素中设置contextPath
<span id="ctx" style="display:none;"><%=request.getContextPath()%></span>
Run Code Online (Sandbox Code Playgroud)
这是准确的,并且在加载页面时不需要任何脚本执行.但是在需要访问contextPath时确实需要DOM查询.如果您非常关心性能,则可以缓存DOM查询的结果.
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));
};
Run Code Online (Sandbox Code Playgroud)
加载页面时不需要执行任何脚本,也可以根据需要缓存结果.但这只有在您知道上下文路径是单个目录时才有效 - 而不是根目录(/)或多个目录down(/mypath/iscomplicated/).
我倾向于哪种方式
我喜欢隐藏的DOM元素,因为它不需要在页面加载时执行JavaScript代码.只有当我需要contextPath时,我才需要执行任何操作(在这种情况下,运行DOM查询).
Mik*_*Lin 64
基于评论中的讨论(特别是来自BalusC),可能不值得做比这更复杂的事情:
<script>var ctx = "${pageContext.request.contextPath}"</script>
Run Code Online (Sandbox Code Playgroud)
Ced*_*mon 42
知道了:D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Run Code Online (Sandbox Code Playgroud)
重要说明:仅适用于"根"上下文路径.不适用于"子文件夹",或者上下文路径中包含斜杠("/").
小智 5
我认为通过将数字1与调用类似于3的函数相结合,您可以实现所需的目标.
您不希望在页面加载时执行脚本,而是希望稍后调用函数?很好,只需创建一个函数,返回您在变量中设置的值:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
Run Code Online (Sandbox Code Playgroud)
它是一个函数,所以它不会被执行,直到你实际调用它,但它直接返回值,而不需要进行DOM遍历或修改URL.
此时我同意@BalusC使用EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
Run Code Online (Sandbox Code Playgroud)
或者取决于JSP回退到JSTL的版本:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
Run Code Online (Sandbox Code Playgroud)
小智 5
Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130594 次 |
| 最近记录: |