你如何以正确的方式从JavaScript获取contextPath? [英] How do you get the contextPath from JavaScript, the right way?

查看:150
本文介绍了你如何以正确的方式从JavaScript获取contextPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用基于Java的后端(即servlet和JSP),如果我需要来自JavaScript的contextPath,建议的模式是什么,为什么?我可以想到一些可能性。我错过了吗?

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?

1。将SCRIPT标记刻录到将其设置为某个JavaScript变量的页面中

<script>var ctx = "<%=request.getContextPath()%>"</script>

这是准确的,但在加载页面时需要执行脚本。

This is accurate, but requires script execution when loading the page.

2。在一些隐藏的DOM元素中设置contextPath

<span id="ctx" style="display:none;"><%=request.getContextPath()%></span>

这是准确的,加载页面时不需要执行任何脚本。但是在需要访问contextPath时确实需要DOM查询。如果你非常关心性能,可以缓存DOM查询的结果。

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.

3。尝试通过检查 document.URL 或BASE标记

3. Try to figure it out within JavaScript by examining document.URL or the BASE tag

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));
};

加载页面时不需要执行任何脚本,如果加载页面,也可以缓存结果必要。但这只有在你知道你的上下文路径是一个目录时才有效 - 而不是根目录( / )或多个目录下来( / mypath / iscomplicated / )。

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/).

我倾向于哪种方式

我喜欢隐藏的DOM元素,因为它不需要在页面加载时执行JavaScript代码。只有当我需要contextPath时,我才需要执行任何操作(在这种情况下,运行DOM查询)。

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).

推荐答案

基于在评论中的讨论中(特别是来自BalusC),可能不值得做比这更复杂的事情:

Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:

<script>var ctx = "${pageContext.request.contextPath}"</script>

这篇关于你如何以正确的方式从JavaScript获取contextPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆