项目http://localhost:8080/myproj
下面页面代码可以直接运行
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.mockjax.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib//jquery.form.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="s()">点击这里</button>
<script>
function myFunction()
{
//获取当前网址,如: http://localhost:8080/myproj/view/my.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: myproj/view/my.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8080
var localhostPaht=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/myproj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
//得到了 http://localhost:8080/myproj
var realPath=localhostPaht+projectName;
return realPath;
//alert(realPath);
}
function s(){
var a = myFunction();
alert(a); //直接弹出 http://localhost:8080/myproj
}
</script>
</body>
</html>