第一种方法:
在jsp 中加入java代码
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
在JS中调用var basePath ='<%basePath%>'
或者
$.ajax({
type:"POST",
url:"<%=request.getContextPath()%>/xxxx",
data:{},
async: false,
dataType: "json",
contentType:'application/json;charset=UTF-8',
success:function(result){
}
})
第二种方法:
采用EL表达式
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
request.setAttribute("basePath", basePath);
在jsp 的script中 var basePath="${basePath}";
注意大括号两边的双(单)引号不能少。
第三种方法:
在单独的js文件中
function getContextPath() {
var pathName = document.location.pathname;
var index = pathName.substr(1).indexOf("/");
var result = pathName.substr(0,index+1);
return result;
}