那一抹温暖的阳光,是我们永恒的向往。
www.webbar.cn

原生Ajax封装随笔

原生Ajax封装随笔

XMLHttpRequest 对象用于和服务器交换数据。我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
open(method,url,async)
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)

send(string)
string:仅用于 POST 请求
注:如果需要像 HTML 表单那样 POST 数据,需设置 setRequestHeader() 来添加 HTTP 头,然后在 send() 方法中规定您希望发送的数据:XMLHttpRequest.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);示例如下代码58行所示。
var Factory = {
create: function() {
return function() { this.init.apply(this, arguments); }
}
}var Ajax = Factory.create();

Ajax.prototype = {
init: function (successCallback, failureCallback) {
this.xhr = this.createXMLHttpRequest();
var xhrTemp = this.xhr;
var successFunc = null;
var failFunc = null;

if (successCallback != null && typeof successCallback == “function”) {
successFunc = successCallback;
}

if (failureCallback != null && typeof failureCallback == “function”) {
failFunc = failureCallback;
}

this.get.apply(this, arguments);
this.post.apply(this, arguments);

this.xhr.onreadystatechange = function () {
if (xhrTemp.readyState == 4) {
if (xhrTemp.status == 200) {
if (successFunc != null) {
successFunc(xhrTemp.responseText, xhrTemp.responseXML);
}
}
else {
if (failFunc != null) {
failFunc(xhrTemp.status);
}
}
}
}
},
get: function (url, async) {
this.xhr.open(“GET”, url, async);
this.xhr.send();
},
createXMLHttpRequest: function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
return new ActiveXObject(“Microsoft.XMLHTTP”);
}

throw new Error(“Ajax is not supported by the browser!”);
},
post: function (url, data, async) {
this.xhr.open(“POST”, url, async);
this.xhr.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
this.xhr.send(data);
},
random: function (length) {
var array = new Array(“0″, “1”, “2”, “3”, “5”, “6”, “7”, “8”, “9”);
var len = parseInt(length);
var key = “”;

for (var i = 0; i < len; i++) {
key += Math.floor(Math.random() * 10);
}

return key;
}
}

对于GET与POST方法使用如下:
function get() {
var ajax = new Ajax(success,fail);
ajax.get(“Scripts/Util.js”, true);
}function post() {
var ajax = new Ajax(success, fail);
ajax.post(“AjaxService.asmx/GetArgs”,”name=jasen”, true);
}

function success(responseText, responseXML) {
alert(“result:” + responseText);
}

function fail(status) {
alert(“status:” + status);
}

时间:2013-10-19

Comments are closed.

Search