一个封装的AJAX类
来源:爱站网时间:2019-01-12编辑:网友分享
不知道你是否跟爱站技术频道的小编一样,給自己定个小目标,在年前写个一个封装的AJAX类,AJAX已然成为了前端开发最重要的“工具”之一,快跟随爱站小编一起往下了解吧。
不知道你是否跟爱站技术频道的小编一样,給自己定个小目标,在年前写个一个封装的AJAX类,AJAX已然成为了前端开发最重要的“工具”之一,快跟随爱站小编一起往下了解吧。
用法:
new Ajax().Request(url,cmd,async,method,postString,title)
参数:
url: 请求页面URL(必填)
cmd: 返回值处理函数(必填)
async: 是否异步 ,(ture|false), 默认true
method: 请求方式,(post|get), 默认get
postString: 请求方式为post时,请求内容
title: 请求内容标题
复制代码 代码如下:
// Ajax 封装 2007-3-13
function createXMLHttpRequest() {
try {
if (window.XMLHTTPRequest) {
return new XMLHttpRequest();
}
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
catch (e) {alert("XMLHttpRequest对象无法创建!请检查IE安全设置!");}
}
function messageDiv(t)
{
var v = document.createElement("
");
v.innerHTML = "" +
style=\"width:300px;\" id=message>
v.innerHTML = "
" + " var l = document.getElementsByName("message").length; v.style.cssText = "position:absolute;bottom:" + (l*24) + "px;left:0px;display:none"; document.body.appendChild(v); this.clear = function () { document.body.removeChild(v); var msg = document.getElementsByName("message"); for (var i=0;i } } this.showmsg = function (s) { v.style.display = ""; v.all.Span1.innerHTML = s; } } function Ajax() { var x = new createXMLHttpRequest(); this.Request = function (url,cmd,async,method,postString,title) { if (method!="post") method = "post"; else method = "get"; if (async!=true) async = true; else async = false; if (typeof(postString)!="string") postString=""; if (typeof(title)!="string") title="正在获取数据"; else title="正在获取" + title; var msgbox = new messageDiv(title); x.onreadystatechange = function () { if (async) switch (x.readystate) { case 1: msgbox.showmsg("正在初始化连接..."); return; case 2: msgbox.showmsg("正在发送数据..."); return; case 3: msgbox.showmsg("正在接收数据..."); return; case 4: msgbox.showmsg("数据接收完成..."); if (x.status == 200) { cmd(x.responseText); msgbox.clear(); } else { msgbox.showmsg("请求失败," + x.statustext + "(" + x.status + ")"); setTimeout(msgbox.clear,3000); } return; } } x.open (method,url,async); if (method=="post") {msgbox.showmsg("正在接收数据...");x.send(postString);} else x.send(); if (!async) { msgbox.showmsg("数据接收完成..."); cmd(x.responseText); msgbox.clear(); } } } | style=\"padding:2px;border-top:1px solid #e1e1e1;border-left:1px solid #e1e1e1;border-bottom:1px solid #818181;border-right:1px solid #a1a1a1\">
爱站技术小编已经成功完成了年前定下的目标,写下这篇一个封装的AJAX类,你也要努力了喔,更多关于AJAX的内容,可以多多关注下爱站技术频道,我们会不断的更新。
上一篇:Ajax获取页面被缓存的解决方案
下一篇:ajax乱码的一种解决方法