很久之前写的一个小型AJAX的js,放在上面以免以后想玩了找不到了。

//  version : 0.1 beta
// author : __Ajax function __Ajax(url,options){ var xhr = window.ActiveXObject && new window.ActiveXObject('Microsoft.XMLHTTP') || new XMLHttpRequest(); // 默认设置
options.method = options.method || 'GET';
options.onSuccess = options.onSuccess || function () { };
options.onFailure = options.onFailure || function () { };
options.onComplete = options.onComplete || function () { }; // 状态改变
xhr.onreadystatechange = function () { if (xhr.readyState != 4) return;
xhr.status == 200 ? options.onSuccess(xhr.responseText, xhr.responseXML) : options.onFailure(xhr);
options.onComplete();
} xhr.open(options.method, url); /*
beta 代码,备用
// 解决未设置method的值为默认GET
// options.method = options.method || 'GET'
*/ options.method.toUpperCase() == 'POST' && xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(options.data); return xhr;
}

使用起来很方便,大家可以拿来玩玩。呵呵。

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="__Ajax.js"></script>
<script type="text/javascript"> window.onload = function () { __Ajax('index.php', { method: 'post',
data: 'name=aaaa',
onSuccess: function (data) {
alert(data);
},
onFailure: function (xhr) {
alert('error');
} });
} </script> </head>
<body> </body>
</html>

压缩版

function __Ajax(b,a){var c=window.ActiveXObject&&new window.ActiveXObject("Microsoft.XMLHTTP")||new XMLHttpRequest();a.method=a.method||"GET";a.onSuccess=a.onSuccess||function(){};a.onFailure=a.onFailure||function(){};a.onComplete=a.onComplete||function(){};c.onreadystatechange=function(){if(c.readyState!=4){return}c.status==200?a.onSuccess(c.responseText,c.responseXML):a.onFailure(c);a.onComplete()};c.open(a.method,b);a.method.toUpperCase()=="POST"&&c.setRequestHeader("Content-type","application/x-www-form-urlencoded");c.send(a.data);return c};
05-01 06:13