jsにおけるajaxパッケージ

2880 ワード

伝達文字列の形式の使用
htmlページコード:

            //                
            function successFn(obj){
                console.log(obj);
            }
            function errorFn(err){
                console.log(err);
            }
            
            //  ajax      
            ajaxFn('GET','data.json','',successFn,errorFn);
        

jsコード:
//        ajax  
//  :method、data、successFn、errorFn、url
function ajaxFn(method,url,data,successFn,errorFn){
    //    
    var xhr=window.XMLHttpRequest?new XMLHttpRequest():ActiveXObject('Microsoft.XMLHTTP');
    //      
    //             
    method=method.toUpperCase();
    if(method=='GET'){
        xhr.open('GET',url+'?'+data,true);
        xhr.send(null);
    }else if(method=='POST'){
        xhr.open('POST',url,true);
        xhr.send(data);
    }else{
        console.error('    ,       !!!');
    }
    //       
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            //successFn(xhr.responseText);
            //  responseXML      ,        json  xml
            var result=xhr.responseXML?xhr.responseXML:xhr.responseText;
            successFn(result);
        }else if(xhr.status==404){
            errorFn('     ');
        }else if(xhr.status==500){
            errorFn('     ');
        }
    }
}

オブジェクトの形式を使用する:
htmlコード:
         
            ajax({
                method:"get",
                url:"./data.json",
                data:"",
                successFn:function(obj){
                    console.log(obj);
                },
                errorFn:function(err){
                    console.log(err);
                }
            })
        

jsコード:
//            (       ),  ajax  
/**
 *         ,  ajax  
 * @param {object} obj [    ,    ,obj.method:    ,obj.url:
 *     ,obj.data:    ,obj.successFn:    ,obj.errorFn:    ]
 * @return {type} [description]
 */
function ajax(obj){
    var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
    
    method=obj.method.toUpperCase();
    if(method=='GET'){
        xhr.open('GET',obj.url+'?'+obj.data,true);
        xhr.send(null);     
    }else if(method=='POST'){
        xhr.open('POST',obj.url,true);
        xhr.send(obj.data);
    }
    
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            var result=xhr.responseText?xhr.responseText:xhr.responseXML;
            obj.successFn(result);
        }
    }
    
}

![Uploading image_814776.png . . .]