gpt4 book ai didi

javascript - 从javascript获取上下文路径

转载 作者:行者123 更新时间:2023-11-30 08:48:12 25 4
gpt4 key购买 nike

我正在尝试清理一个用 jsp servlet 和 javascript jquery 编写的应用程序。目前在jsp中,写了很多javascripts。我正在尝试将所有这些 javascript 移动到一个单独的 js 文件中。在 jsp 中,它通过 javascript 获取 contextPath,然后使用此 contextPath 执行一些逻辑。是否可以在 javascript 中获取上下文路径?它还在 jsp 中使用了一些类似的代码。我如何将此代码移动到 js 文件?

HTML

 <input type="button" id="cntButton" value="CONTINUE" onclick="javascript: callTest('<%=request.getContextPath()%>/test1/test2/test3.do');"/>

function callTest(pageURL){
}

如果我将函数 callTest(pageURL) 移动到一个 javascript 文件,我如何从 jsp 传递 contextPath?

更新 2

在jsp中,

<%
String firstName= "";

if (sampleBean.getName() != null) {
firstName = sampleBean.getName();
}
%>
<script type="text/javascript">
window.onload=loadVal;

function loadVal() {
document.getElementById('business_name').value = "<%=firstName%>";
}
</script>

我需要将此 loadVal() 移动到另一个 js 文件。那么如何传递从 bean 中获取的“<%=firstName%>”呢?

最佳答案

使用 JSP 将其写入您的页面并在 js 文件中引用。它会起作用。

确保在这段代码之后添加js文件

<script type="text/javascript">

var contextPath='<%=request.getContextPath()%>';

console.log(contextPath);


</script>

<input type="button" id="cntButton" value="CONTINUE" 
onclick="javascript:callTest(contextPath+'/test1/test2/test3.do')" />

或者传递url并添加到callTest函数中

<input type="button" id="cntButton" value="CONTINUE" 
onclick="javascript:callTest('/test1/test2/test3.do')" />

ma​​in.js

function callTest(pageURL)
{
var url=contextPath+pageURL;
//contextPath will be available, if defined in JSP
}

关于javascript - 从javascript获取上下文路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com