学习Jquery里ajax如何原生态面向对象法实现

初学js,好奇jquery里ajax的实现就看了几篇博文,自己动手设计一个面向对象的原生态版本的ajax,以供学习之用,不足之处忘大家批评指正!

一、首先是jquery里ajax的用法

1、$.get

$.get()方法使用GET方式来进行异步请求,它的语法结构为:

$.get( url [, data] [, callback] )

解释一下这个函数的各个参数:

url:string类型,ajax请求的地址。

data:可选参数,object类型,发送至服务器的key/value数据会作为QueryString附加到请求URL中。

callback:可选参数,function类型,当ajax返回成功时自动调用该函数。

2、$.post()

$.post()方法使用POST方式来进行异步请求,它的语法结构为:

$.post(url,[data],[callback],[type])

这个方法和$.get()用法差不多,唯独多了一个type参数,那么这里就只介绍type参数吧,其他的参考上面$.get()的。

type:type为请求的数据类型,可以是html,xml,json等类型,如果我们设置这个参数为:json,那么返回的格式则是json格式的,如果没有设置,就和$.get()返回的格式一样,都是字符串的。

具体可参见博文http://www.cnblogs.com/conmecon/p/3281577.html(ps:感谢作者菜鸟程序员求成长地 提供)

 

自己面向对象法封装的Ajax.js,可以引用到页面中调用,代码如下:

var Ajax = {
xmlHttp: "",
xdr:"",
url: "",
data: "",
IsAsy:true,

//根据不同浏览器创建不同的ajax实例!
xmlHttpCreate: function () {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();//火狐和Opera浏览器或者Chrome
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//ie浏览器
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert(e.message);
}
}
}
return xmlHttp;
},
//实现异步跨域请求,这里有些问题,好像跨域总是出现(No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin //'http://localhost:58575' is therefore not allowed access. The response had HTTP status code 404.)希望大神看到,能帮忙解答
CORS: function (jsonObj) {

Ajax.xdr = Ajax.CreatCORSRequest(jsonObj.method, jsonObj.url);
if (jsonObj.origin) {
Ajax.xdr.setRequestHeader("Access-Control-Allow-Origin", jsonObj.origin);
}
Ajax.xdr.onload = function () {
jsonObj.success(Ajax.xdr.responseText);
};
Ajax.xdr.onerror = function () {
alert("An error");
};
if (jsonObj.data) {
Ajax.xdr.sent(jsonObj.data);
} else {
Ajax.xdr.send(null);
}
},

//自定义get请求,可以直接外部调用,用法如:Ajax.get({url: Ajax.addURLParam("ajax.ashx", "tom jac", "t j"),IsAsy: true,success: //function(responseText) {console.log("success:" + responseText);},error: function (reponseText) {console.log("error:" + reponseText);}})

get: function (jsonObj) {

if (jsonObj.data) {
Ajax.data = jsonObj.data;
}
Ajax.url = jsonObj.url;
if (jsonObj.IsAsy) {
Ajax.IsAsy = jsonObj.IsAsy;
}
Ajax.xmlHttp = Ajax.xmlHttpCreate();
Ajax.xmlHttp.open("get", Ajax.url, Ajax.IsAsy);
Ajax.xmlHttp.send(null);
if (Ajax.IsAsy) {
Ajax.xmlHttp.onreadystatechange = function () {

//XHR对象的readyState属性,该属性表示请求/响应过程中的当前活动阶段0:未初始化,1:启动,已经调用open()方法,但未调用send();2:发送,已经调

//用send()但未接收响应;3:接收,已经接收到部分响应数据;4:完成。可以在客户端使用了
if (Ajax.xmlHttp.readyState == 4) {

//status的属性200表示成功,304表示请求的资源并没有修改,可以直接使用浏览器中缓存的版本,响应也是有效的
if ((Ajax.xmlHttp.status >= 200 && Ajax.xmlHttp.status < 300) || Ajax.xmlHttp.status == 304) {
jsonObj.success(Ajax.xmlHttp.responseText);
} else {
jsonObj.error(Ajax.xmlHttp.responseText);
}
}
}
} else {
if ((Ajax.xmlHttp.status >= 200 && Ajax.xmlHttp.status < 300) || Ajax.xmlHttp.status == 304) {
jsonObj.success(Ajax.xmlHttp.responseText);
} else {
jsonObj.error(Ajax.xmlHttp.responseText);
}
}
},

//面向对象的post实现,用法如:

/*Ajax.post({

data: '{"a":"n"}',
url: "ajax.ashx",
success: function (reponseText) {
// console.log("success:" + reponseText);
var obj = eval("(" + reponseText + ")");
if (obj.success == "ok") {
alert("提交成功");
}
},
error: function (reponseText) {
console.log("error:" + reponseText);
}
});*/


post: function (jsonObj) {
Ajax.data = jsonObj.data;
Ajax.url = jsonObj.url;
Ajax.xmlHttp = Ajax.xmlHttpCreate();
Ajax.xmlHttp.open("post", Ajax.url, true);
Ajax.xmlHttp.setRequestHeader("Content-Type","application/x-www-from-urlencoded");
Ajax.xmlHttp.send(Ajax.data);
Ajax.xmlHttp.onreadystatechange = function () {
if (Ajax.xmlHttp.readyState == 4) {
if ((Ajax.xmlHttp.status >= 200&&Ajax.xmlHttp.status<300)||Ajax.xmlHttp.status==304) {
jsonObj.success(Ajax.xmlHttp.responseText);
} else {
jsonObj.error(Ajax.xmlHttp.responseText);
}
}
}
},
//添加url参数这里把传入的参数固定为“tom jac”这种中间带空格的字符串形式,大家有好的方法欢迎交流
addURLParam: function (url, name, value) {
//var names = [];
//name = "sdfd";
var names = name.split(" ");
var values = value.split(" ");
for (var i = 0; i < names.length; i++) {
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(names[i]) + "=" + encodeURIComponent(values[i]);
}
return url;
},
//创建兼容浏览器的跨域请求
CreatCORSRequest: function (method, url) {
var xhr = new XMLHttpRequest();
if("withCredentials"in xhr)
{
xhr.open(method, url, true);
}else if(typeof XDomainRequest!="undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
};

 

最后引入    <script src="js/Ajax.js"></script>,直接使用Ajax.get({})和Ajax.post({})。

此贴供初学js和熟悉js的面向对象用法的新手使用,不足之处请大家批评指正!

转载于:https://www.cnblogs.com/ddcouples/p/5511092.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值