我来给你处理
创建 XMLHttpRequest 对象
function createXMLHttpRequest() {
if (window.ActiveXObject) { // IE
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} else { // not IE
xhr = new XMLHttpRequest();
}
}
和服务器端建立连接
// post请求
xhr.open("post", "/myAjax2/example1/example1.jsp");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
// xhr.send("name=" + name);
// get请求
xhr.open("get", "/myAjax2/example1/example1.jsp?name="+name);
// xhr.send(null);
指定回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) { // 响应已经完毕
if (xhr.status == 200) { // 200
// 获取返回值
var text = xhr.responseText;
// 将返回值写入到指定位置
document.getElementById("nametip").innerHTML = text;
// alert(text);
} else { // 404 500
alert(xhr.status + " " + xhr.statusText);
}
}
};
// HTTP就绪状态,表示请求的状态或情形
/**
* readyState
* HTTP就绪状态,表示请求的状态或情形。在Ajax应用程序中需要了解五种就绪状态,但通常只使用状态4:
* 0:请求没有发出(在调用 open() 之前)
* 1:请求已经建立但还没有发出(调用 send() 之前)
* 2:请求已经发出正在处理之中(这里通常可以从响应得到内容头部)
* 3:请求已经处理,响应中有部分数据可用,但是服务器还没有完成响应
* 【 4:响应已完成,可以访问服务器响应并使用它 】
*/
// 响应的状态码
/**
* 200
* 404
* 500
*/
发送请求
// post请求
xhr.send("name=" + name);
// get请求
xhr.send(null);