【问题标题】:JavaScript file not loading in .jsp fileJavaScript 文件未加载到 .jsp 文件中
【发布时间】:2017-08-22 23:34:13
【问题描述】:

目前我正在前端编程,但遇到了我的 javascript 文件无法加载的问题。我的文件是 .jsp 因为 scala/scalatra 后端。我有我的 index.jsp,其中我在顶部包含我的头文件,在底部包含我的页脚。

我这样包含它们:

<jsp:include page="header.jsp"/>
// CODE //
<jsp:include page="footer.jsp"/>

我的标题是这样的:

<!-- HEADER -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="styles/cssfile.css">
    <link rel="stylesheet" href="css/cssfile.css">
</head>
<body>

我的页脚看起来像这样:

  <!-- FOOTER -->
      <script type="text/javascript" src="js/jquery.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
</body>
</html>

我的 main.js 看起来像这样:

$(document).ready(function () {
'use strict';
$(function() {

    $('a[href*=#]:not([href=#])').click(function () {

          if (
                  location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
                || location.hostname == this.hostname
            ) {

            var target = $(this.hash);

            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

            if ( target.length ) {

                  $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
                  return false;

            }

          }

    });

});

});

我的文件结构是这样的:

css
  -cssfile1
  -cssfile2
js
  -jquery.js
  -main.js
header.jsp
index.jsp
footer.jsp

src 先生的路线应该是正确的,当我检查站点的源代码时,我可以看到 main.js 文件并单击它,它是正确的 js。 我试过 console.log("test");什么都没有出现,所以它不会加载。 如您所见,我添加了带有 jquery javascript 的 jquery.js,并首先将其添加到页脚中。

所以我想要的是我的 main.js 应该加载。

提前致谢:)

【问题讨论】:

  • 实际发送到浏览器的最终 HTML 是什么?在浏览器的调试工具中,是否发出了对.js 文件的请求?服务器的响应是什么?您的.js 中是否还有另一个错误阻止console.log("test"); 执行?显示足够的代码来重现问题。

标签: javascript jquery html scala


【解决方案1】:

JSP EL 提供了一个变量 (${pageContext.request.contextPath}),可以在设计时使用它来帮助在运行时解析到正确的路径。试试这个可能会有所帮助,您使用的是正确的 jquery 库吗?

<script type="text/javascript" src="${pageContext.request.contextPath}/js/main.js"></script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">

【讨论】:

  • 它对我不起作用,我的 javascript 仍然不起作用,我没有得到 console.log("test"); 的响应
  • 你用的是正确的jquery吗我加了一个CDN给你试试
  • 那是我现在在页脚中的方式,但我仍然无法工作。在控制台中我得到:GET localhost:8080/js/main.js as an 404
  • 第一个链接 为我工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2011-04-19
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 2019-03-06
相关资源
最近更新 更多