一、
以支持多种浏览器的方式创建 XMLHttpRequest 对象
var xmlHttp = false;
if(window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlHttp = false;
}
}
}
else if (window.XMLHttpRequest) {
try{
xmlHttp= new XMLHttpRequest();
} catch(fail){
xmlHttp= false ;
}
}
if (!xmlHttp)
alert("Error initializing XMLHttpRequest!");
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
if ((name == null) || (name == "")) {
return;
}
if ((password == null) || (password == "")) {
return;
}
// Build the URL to connect to
var url = "/ajax/AjaxServlet?name=" + escape(name) + "&password=" + escape(password);
// Open a connection to the server
xmlHttp.open("HEAD", url, true);
// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage;
// Send the request
xmlHttp.send(null);
}
xmlHttp
(要记住,这是 XMLHttpRequest
对象实例)的 onreadystatechange
属性可以告诉服务器在运行完成
后(可能要用五分钟或者五个小时)做什么。因为代码没有等待服务器,必须让服务器知道怎么做以便您能作出响应。在这个示例中,如果服务器处理完了请求,一个特殊的名为 updatePage()
的方法将被触发。
function updatePage() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
// alert("updatePage() called with ready state of " + xmlHttp.readyState);
alert(xmlHttp.getAllResponseHeaders());
} else if (xmlHttp.status == 404) {
alert ("Requested URL is not found.");
} else if (xmlHttp.status == 403) {
alert("Access denied.");
} else
alert("status is " + xmlHttp.status);
}
// if (xmlHttp.readyState == 4) {
// var response = xmlHttp.responseText;
// document.getElementById("test").value = response;
// alert("updatePage() called with ready state of " + xmlHttp.readyState);
// }
}
本文介绍如何使用JavaScript创建跨浏览器兼容的XMLHttpRequest对象,并通过GET方法向服务器发起Ajax请求。文中详细展示了如何构建请求URL、设置回调函数以及处理不同状态码。
1029

被折叠的 条评论
为什么被折叠?



