(
function
(){
if
(typeof window.
$JSON
== 'undefined'){
window.
$JSON
= {};
};
$JSON
._ajax =
function
(config){
config = config[0] || {};
this.url = config.url || '';
this.type = config.type || 'xhr';
this.method = (this.type == 'json') ? 'GET' : config.method.toUpperCase() || 'GET';
this.param = config.param || null;
this.callback = config.callback || {};
this.XHR = null;
if
(typeof window._
$JSON_callback
== 'undefined'){
window._
$JSON_callback
= {};
}
this._createRequest();
};
$JSON
._ajax.prototype = {
_createXHR :
function
(){
var
methods = [
function
(){
return
new
XMLHttpRequest(); },
function
(){
return
new
ActiveXObject('Msxml2.XMLHTTP'); },
function
(){
return
new
ActiveXObject('Microsoft.XMLHTTP'); }
];
for
(
var
i = 0, l = methods.length; i < l; i++){
try
{
methods[i]();
}
catch
(e){
continue
;
}
this._createXHR = methods[i];
return
methods[i]();
}
},
_createRequest :
function
(){
return
(this.type == 'json') ? this._setJSONRequest() : this._setXHRRequest();
},
_setXHRRequest :
function
(){
var
_this = this;
var
param = '';
for
(
var
i in this.param){
if
(param == ''){
param = i+'='+this.param[i];
}
else
{
param+= '&'+i+'='+this.param[i];
}
}
this.XHR = this._createXHR();
this.XHR.onreadystatechange =
function
(){
if
(_this.XHR.readyState == 4 && _this.XHR.status == 200){
_this.callback.success(_this.XHR.responseText);
}
else
{
_this.callback.failure('重新操作');
}
};
this.XHR.open(this.method, this.url, true);
this.XHR.setRequestHeader(
"Content-Type"
,
"application/x-www-form-urlencoded; charset=utf-8"
);
this.XHR.send(param);
},
_setJSONRequest :
function
(){
var
head = document.getElementsByTagName('head')[0];
var
script = document.createElement('script');
var
fun = this._setRandomFun();
var
_this = this;
var
param = '';
for
(
var
i in this.param){
if
(param == ''){
param = i+'='+this.param[i];
}
else
{
param+= '&'+i+'='+this.param[i];
}
}
script.type = 'text/javascript';
script.charset = 'utf-8';
if
(head){
head.appendChild(script);
}
else
{
document.body.appendChild(script);
}
window._
$JSON_callback
[fun.id] =
function
(data){
_this.callback.success(data);
setTimeout(
function
(){
delete
window._
$JSON_callback
[fun.id];
script.parentNode.removeChild(script);
}, 100);
};
script.src = this.url+'?callback='+fun.name+'&'+param;
},
_setRandomFun :
function
(){
var
id = '';
do
{
id = '
$JSON
'+Math.
floor
(Math.random()*10000);
}
while
(window._
$JSON_callback
[id])
return
{
id : id,
name : 'window._
$JSON_callback
.'+id
}
}
};
window.
$JSON
.ajax =
function
(){
return
new
$JSON
._ajax(arguments);
}
})();