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

查看:20
本文介绍了您如何以正确的方式从 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天全站免登陆