第一種方法:java
在jsp 中加入java代碼ajax
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";json
在JS中調用var basePath ='<%basePath%>'app
或者jsp
$.ajax({
type:"POST",
url:"<%=request.getContextPath()%>/xxxx",
data:{},
async: false,
dataType: "json",
contentType:'application/json;charset=UTF-8',
success:function(result){async
}
})url
第二種方法:ip
採用EL表達式get
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
request.setAttribute("basePath", basePath);io
在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; }