加载资源失败:服务器响应状态为404(未找到)

问题描述:

我正在关注有关Javascript和Ajax的Lynda教程,并在主题为“使用同步XHR请求”的主题上挂起了这个问题。加载资源失败:服务器响应状态为404(未找到)

基本上HTML文件是:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>JavaScript AJAX</title> 
</head> 
<body> 
<script src = "script.js"></script> 
</body> 
</html> 

和JavaScript文件是:

var request = new XMLHttpRequest(); 
request.open('GET', 'data.txt', false); 
request.send(); 
console.log(request); 

data.txt文件具有的 “Hello World” 就可以了。

路径到项目文件

C:/wamp/www/ajax/index.html 
C:/wamp/www/ajax/script.js 

当我打开wampserver本地主机,并做检查元素我得到这个上面的错误说“无法加载资源:服务器用状态404(未回应找到)“

主线程上的同步XMLHttpRequest已弃用,因为它对最终用户的体验有不利影响。如需更多帮助,请查询http://xhr.spec.whatwg.org/http://localhost/ajax/script.js无法加载资源:服务器与404状态(未找到)

的XMLHttpRequest

onabort: null 
onerror: null 
onload: null 
onloadend: null 
onloadstart: null 
onprogress: null 
onreadystatechange: null 
ontimeout: null 
readyState: 4 
response: "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">↵<html><head>↵<title>404 Not Found</title>↵</head><body>↵<h1>Not Found</h1>↵<p>The requested URL /ajax/data.txt was not found on this server.</p>↵<hr>↵<address>Apache/2.4.9 (Win32) PHP/5.5.12 Server at localhost Port 80</address>↵</body></html>↵" 
responseText: "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">↵<html><head>↵<title>404 Not Found</title>↵</head><body>↵<h1>Not Found</h1>↵<p>The requested URL /ajax/data.txt was not found on this server.</p>↵<hr>↵<address>Apache/2.4.9 (Win32) PHP/5.5.12 Server at localhost Port 80</address>↵</body></html>↵" 
responseType: "" 
responseURL: "http://localhost/ajax/data.txt" 
responseXML: null 
status: 404 
statusText: "Not Found" 
timeout: 0 
upload: XMLHttpRequestUpload 
withCredentials: false 
__proto__: XMLHttpRequest 

hungup与话题这个问题的 “使用同步XHR请求” 作出回应。

所以不要这样做。

request.open('GET','data.txt',false);

false的意思是“不要发出异步请求”。把它拿出来。

request.open('GET', 'data.txt'); 

然后,您需要使用事件侦听器,而不是等待浏览器等待响应返回,然后继续执行JavaScript。

request.addEventListener("load", function (event) { 
    console.log(this); 
}); 

那当然了,有没有关系:

无法加载资源:服务器与404(未找到)状态

回应这只是表示http://localhost表示/ajax/data.txt不存在。

+0

谢谢!它运行良好,正如你所说的那样,它无关:“无法加载资源:服务器响应状态为404(未找到)”。唯一的问题是我以名称“data.txt”保存了我的文本文档,但实际上它只能被命名为“data”,因为它可以保存为data.txt,它是一个文本文档。 –