【问题标题】:.load() method in jquery give me 404 - Not Found errorjquery 中的 .load() 方法给我 404 - Not Found 错误
【发布时间】:2026-01-07 02:50:02
【问题描述】:

我有一个简单的页面,我需要将 .html 文件加载到 DIV,但我总是有 404 NOT FOUND

我的 JSP 文件在同一个文件夹中有一个名为 demo_test.txt 的文件,我需要将此文件加载到 ID="div1" 的 div 中

这里是代码:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
   // $("#div1").load("demo_test.txt");
   $("#div1").load("demo_test.txt", function(responseText, statusText, xhr)
        {
                if(statusText == "success")
                        alert("Successfully loaded the content!");
                if(statusText == "error")
                        alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
        });

  });

});

</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>

</body>
</html>

【问题讨论】:

  • 您是否尝试使用您希望找到的网址浏览文件?
  • 您是否在浏览器调试器的网络检查器选项卡中检查了它试图加载的文件?然后点击右键“在新标签页中打开”就可以了?
  • 为了使其工作,该文件必须与调用脚本的 HTML 页面位于完全相同的目录中。是这样吗?
  • 是的,它在jsp页面的同一个文件夹中

标签: jquery ajax


【解决方案1】:

就像克劳迪奥·雷迪所说...

您正在尝试加载相对于您所在路径的文件。尝试对文件路径进行硬编码,然后在浏览器中查看它,然后它应该会加载。

所以你的行将是这样的(如果文件位于 WEBROOT /MY_APP/Files)

$("#div1").load("/MY_APP/Files/demo_test.txt", function(responseText, statusText, xhr)

或完整路径

$("#div1").load("http://MyWebsite.com/MY_APP/Files/demo_test.txt", function(responseText, statusText, xhr)

【讨论】:

  • demo_test.txt 和 jsp 页面都在文件夹中:web pages\WEB-INF\jsp 所以请问我应该如何写 url
  • 我使用了这个网址“localhost:8080/RSS/WEB-INF/jsp/htmlForm.html”,但它仍然无法正常工作
  • 试着把 // 放在它前面,当你不安全时这将从 http 获取,当你安全时从 https 获取.. 所以这个:$("#div1").load("/ /localhost:8080/RSS/WEB-INF/jsp/htmlForm.html", 函数(responseText, statusText, xhr)