ajax 的 xmlhttp request对象的 面向对象封装
在做这个网站的时候, 有些地方要用到简单的ajax效果。用框架也太不麻烦了,所以索性自己封装了一个简洁的ajax的类,当然也和大家分享一下:
//ajax.js代码start
function xmlhttpcls(url, verb)
{
var request = get_xmlhttp_obj();
this.callback = null;
var params = [];
//
this.add = function (pname, pvalue)
{
params[params.length] = new param(pname, pvalue);
}
//
this.getText = function()
{
return request.responseText;
}
//
this.getXml = function()
{
return request.responseXML;
}
//
this.send = function()
{
var callback = this.callback;
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
if(request.status == 200)
callback();
else
{
document.write("ERR[" + request.status + "] : " + request.statusText
+ "<br>" + url + "<br>" + getUrlParamString(params));
}
}
};
if (verb != null && verb == "post")
{
request.open("POST",url,true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.setRequestHeader("If-Modified-Since","0");
request.send(getUrlParamString(params));
}
else
{
var urlparams = getUrlParamString(params);
if (urlparams != null)
{
urlparams = "?" + urlparams;
}
request.open("GET",url + urlparams,true);
request.setRequestHeader("If-Modified-Since","0");
request.send(null);
}
}
//
var getUrlParamString = function(ps)
{
var urlString = null;
if (ps.length > 0)
{
urlString = "";
for (var i = 0 ; i < ps.length; i++)
{
urlString = urlString + (i == 0 ? "" : "&");
urlString += ps[i].name + "=" + ps[i].value;
}
}
return urlString;
}
//
}
function param(pname, pvalue)
{
this.name = pname;
this.value = pvalue;
}
function get_xmlhttp_obj()
{
var http_request = null;
if(window.XMLHttpRequest) //其他浏览器 Mozilla,
{
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType)
{
http_request.overrideMimeType("text/xml");
}
}
else if(window.ActiveXObject) //IE
{
try
{
http_request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
return http_request;
}
//ajax.js代码end
下面是HTML页面中的调用代码
var xmlhttp = new xmlhttpcls("请求的url", "post"); // 若第二个参数不填或者写"get"则为get方式
xmlhttp.add("参数1", "参数1的值");
xmlhttp.add("参数2", "参数1的值");
xmlhttp.callback = function()
{
var temptext = xmlhttp.getText();
var tempXmlDOM = xmlhttp.getXml();
}
xmlhttp.send();
是不是很有点简单 。