在.js文件中获取绝对路径的方法

来源:互联网 发布:linux文件执行权限 编辑:程序博客网 时间:2024/04/29 05:13

在不同页面请求相同的相对路径时,有的页面是不能获得响应的,如果将请求地址设置为绝对路径,那么无论在什么页面都能访问到.

如果在jsp中我们可以用base标签.

<% String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><base href="<%=basePath%>"
或者在请求路径前面加上el表达式

${pageContext.request.contextPath}/

但是,如果在js文件中,我们就无法使用到el表达式了.这时我们可以使用jstl表达式,将工程名路径放到作用域中,然后放到变量里,这时在js文件中就能通过获取变量值来最终得到绝对路径.

在jsp的头文件中添加

<c:set var="contextPath" value="${pageContext.request.contextPath}" scope="application"/>      <script>          var contextPath = "${contextPath}";      </script>  
然后就能在js中得到值,例如:

$(".logged").hover(function(){$.ajax({url:contextPath+"/loan/myAvailableMoney", //这里获取到了${pageContext.request.contextPath}success:function(data){if(data.errorMessage=="ok"){$("#frame_top").html(data.availableMoney);}else{$("#frame_top").html("0");}},error:function(){$("#frame_top").html("--");}});






原创粉丝点击