我需要通过Ajax调用在浏览器中使用servlet程序显示hello world但是点击按钮我不会显示它可能是这个错误的原因:
Uncaught NetworkError:无法在'XMLHttpRequest'上执行'send':无法加载'file:/// D:/ workspace / Poc_Ajax / WebContent / WEB-INF / HelloWorld'。
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "HelloWorld", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>
答案 0 :(得分:1)
要运行servlet程序,您需要向配置为执行servlet的Web服务器发出HTTP请求。
您的Ajax URL(显示在错误消息中)以file://
开头,因此您尝试处理本地文件而不是网络服务器。
安装网络服务器(例如Tomcat)。从中加载HTML文档。确保"HelloWorld"
是从该HTML文档到servlet URL的相对URI。