1、问题描述
想在项目中使用jquery,于是从jquery官网下载了最新版本(手动从浏览器中复制到本地的js文件中),并在html文件中添加了引用。目录及引用情况如图。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<script src="../static/jquery.min.js"></script>
<script type="text/javascript">
function btnLoginClick() {
if (typeof jQuery !== 'undefined') {
alert("Loaded success.");
} else {
alert ("Not yet.");
}
}
</script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>
运行起来一直提示jQuery没有加载。
将script引用换成远程引用就没有问题。
<script src="http://code.jquery.com/jquery-latest.js"></script>
2、解决方案
网上搜了很多资料,有说是从浏览器copy的文本有问题的,但我直接下载别人的js文件也不行。有说是文件编码格式的问题的,但是我确认了html文件和js文件编码格式都是utf-8,加载还是失败。
后来搜资料时发现别人引用js文件的路径跟自己的不太一样(我是直接将js文件拖到html文件中,IDE自己生成的引用路径),遂怀疑是路径的问题。将自己写的脚本移到单独的js文件中,再在html中添加引用。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<script src="../static/jquery.min.js"></script>
<script src="../static/myScript.js"></script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>
发现一样加载失败,故确定是路径的问题。
搜索正确的路径引用的姿势,参考这篇文章,将路径改为
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<script src="./jquery.min.js"></script>
<script src="./myScript.js"></script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>
加载OK。
PS:
另外一个项目中按照上面设置还是加载失败,发现是使用了shiro的缘故。需要在shiro的FilterChain中添加拦截规则,让静态资源可以匿名访问。
@Bean
ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/js/**", "anon");
definition.addPathDefinition("/login", "anon");
definition.addPathDefinition("/**", "authc");
return definition;
}