use*_*057 1 javascript jquery jsp
我试图清理一个用jsp servlet和javascript,jquery编写的应用程序.目前在jsp中,有很多javascripts写的.我试图将所有这些javascripts移动到一个单独的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){
}
Run Code Online (Sandbox Code Playgroud)
如果我将函数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>
Run Code Online (Sandbox Code Playgroud)
我需要将此loadVal()移动到另一个js文件.那么如何传递从bean中获取的"<%= firstName%>"?
使用JSP在页面中写入此内容并在js文件中引用.它会工作.
确保在此代码后添加js文件
<script type="text/javascript">
var contextPath='<%=request.getContextPath()%>';
console.log(contextPath);
</script>
Run Code Online (Sandbox Code Playgroud)
和
<input type="button" id="cntButton" value="CONTINUE"
onclick="javascript:callTest(contextPath+'/test1/test2/test3.do')" />
Run Code Online (Sandbox Code Playgroud)
或传递url并将其添加到callTest函数中
<input type="button" id="cntButton" value="CONTINUE"
onclick="javascript:callTest('/test1/test2/test3.do')" />
Run Code Online (Sandbox Code Playgroud)
main.js
function callTest(pageURL)
{
var url=contextPath+pageURL;
//contextPath will be available, if defined in JSP
}
Run Code Online (Sandbox Code Playgroud)