利用javascript实现原生简单ajax的方法。
实现ajax之前必须要创建一个 XMLHttpRequest (IE6↑)对象。如果不支持创建该对象的浏览器,则需要创建 ActiveXObject(IE6),具体方法如下:
var objectRequest;
function createXmlHttpRequest() {
if ( window.XMLHttpRequest) {
objectRequest=new XMLHttpRequest();
} else if ( window.ActiveXObject )
objectRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
(1)实现简单的ajax get请求:
function doGet(url){
createxmlHttpRequest();
objectRequest.open("GET",url,true);
objectRequest.send(null);
objectRequest.onreadystatechange = function() {
if (( objectRequest.readyState == 4) && ( objectRequest.status == 200)) {
//TODO请求成功回调代码
} else {
//TODO 请求失败回调代码
}
}
}
createxmlHttpRequest();
objectRequest.open("GET",url,true);
objectRequest.send(null);
objectRequest.onreadystatechange = function() {
if (( objectRequest.readyState == 4) && ( objectRequest.status == 200)) {
//TODO请求成功回调代码
} else {
//TODO 请求失败回调代码
}
}
}
(2)实现简单的ajax post请求:
function doPost(url,data){
createxmlHttpRequest();
objectRequest.open("POST",url,true);
objectRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
objectRequest.send(data);
objectRequest.onreadystatechange = function() {
if (( objectRequest.readyState == 4) && ( objectRequest.status == 200)) {
//TODO 请求成功回调代码
} else {
//TODO 请求失败回调代码
}
}
}