当js在jsp页面中写的时候没有任何问题如下所示:
function deleteP(obj){if(confirm("你真舍得丢弃我吗?")){//发送请求location.href="${pageContext.request.contextPath }/deleteProductById?pid="+obj;}}
但是将js提取出来放到一个单独的js页面中引入的时候,就报错了,这是因为${pageContext.request.contextPath }在js中不起作用
按照下面要求将路径改成绝对路径即可跳转成功
var url = window.location; // 获取当前页面的地址var protocol = location.protocol //获取http或httpsvar host =url.host //获取当前JSP页面的地址栏IP和端口号 即://localhost:8080var contextPath = url.pathname.split("/")[1]; //获取项目名 即:showproductvar basePath = protocol +"//"+host+"/"+contextPath; //即:http://localhost:8080/showproductfunction deletep(obj){if(confirm("你舍得舍弃我吗?")){location.href=basePath+"/deleteProductById?pid="+obj;}}
当前页面的网址为:
外部js文件引入
1、直接引用:
根据项目的目录结构,项目目录结构如图:引用方式为:
<script type="text/javascript"src="js/jquery-3.0.0.min.js"></script>
2、通过EL表达式引入:
<%@ page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"isELIgnored="false"%><%@ taglib uri="/jsp/jstl/core"prefix="c"%><c:set value="${pageContext.request.contextPath}"var="path"scope="page"/><script type="text/javascript"src="${path}/js/jquery-3.0.0.min.js"></script>
3、通过java引入:
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><script type="text/javascript"src="<%=basePath%>/js/jquery-3.0.0.min.js"></script>