原生js封装的ajax请求

function ajax(json){
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //解析所传递过来的数据
    var query = json.url.indexOf('?')===-1?'?':'&';
    for(prop in json.data){
        query+=prop+'='+json.data[prop]+'&';
    }
    query = query.slice(0,-1);
    if(json.type ==='get'){
        json.url+=query;
        xhr.open(json.type,json.url,true);
        xhr.send(null);

    }else if(json.type === 'post'){
        xhr.open(json.type,json.url,true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send(JSON.stringify(query));
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState===4){
            if(xhr.status >= 200 && xhr.status<300 || xhr.status===304){
                json.success(xhr.responseText);
            }else{
                json.error(xhr.status);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hahahahahahahaha__1/article/details/81875132