首页 > 代码库 > ajax方法简单实现

ajax方法简单实现

//option {url,medthod,type,data,fSuccess,fError}
function ajax(option) {
    var xhr = window.XMLHttpRquest ? new XMLHttpRquest() : new ActiveXObject(‘Microsoft.XMLHTTP‘);
    var body = option.method.toLowerCase() == ‘get‘ ? null : option.data;
    xhr.open(option.method,url);
    xhr.send(body);    
    xhr.onreadystatechange = function(){
        if(xhr.readystate == 4 && xhr.status == 200){
            if(option.fSuccess){
                switch (option.type) {
                    case ‘json‘:
                        option.fSuccess(JOSN.parse(xhr.responseText));
                        break;
                    default:
                        option.fSuccess(xhr.responseText);
                        break;
                }
            }
        }
        else{
            option.fError({
                status:xhr.status,
                statusText:xhr.statusText
            })
        }
    }
}

 

ajax方法简单实现