Skip to content

Instantly share code, notes, and snippets.

@titanew
Last active December 17, 2015 14:29
Show Gist options
  • Save titanew/5624695 to your computer and use it in GitHub Desktop.
Save titanew/5624695 to your computer and use it in GitHub Desktop.
简易ajax封装
var myAjax = {
// XMLHttpRequest IE7+, Firefox, Chrome, Opera, Safari ; ActiveXObject IE6, IE5
xhr: window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'),
get: function (url, callback) {
this.xhr.open('get', url);
this.onreadystatechange(callback, this.xhr);
this.xhr.send(null);
},
post: function (url, data, callback) {
this.xhr.open('post', url);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.onreadystatechange(callback, this.xhr);
this.xhr.send(data);
},
onreadystatechange: function (func, _xhr) {
_xhr.onreadystatechange = function () {
if (_xhr.readyState == 4) {
if (_xhr.status == 200) {
func(_xhr.responseText);
}
}
}
}
}
//usaege:
$('#btn_nowTime1').bind('click', null
, function () {
myAjax.post('AjaxHandler.ashx', 'func=GetServerTime'
, function (data) {
if (data)
alert(data);
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment