原生js 完整封装ajax

最近开始看了看跟Node相关的内容,联想到了前后台的交互,于是记录一下自己封装的ajax,初学者,写的糙,望见谅~~


function ajax(json){

    if(window.XMLHttpRequest){
        var ajax = new XMLHttpRequest();
    }
    else{
        var ajax = new ActiveXObject( "Microsoft.XMLHTTP" );
    }

    if(json.type=='get'){
        ajax.open('get',json.url+'?'+JsonToString(json.data),true);
        ajax.send();
    }
    else if(json.type=='post'){
        ajax.open('post',json.url,true);
        ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        ajax.send(JsonToString(json.data));
    }
    
    ajax.onreadystatechange = function(){
        if(ajax.readyState == 4){
            if(ajax.status>=200 && ajax.status<300 || ajax.status == 304){
                json.success(ajax.responseText);

            }
            else{
                json.error && json.error();
            }
        };
    };


    function JsonToString(json){
        var arr = [];
        for(var i in json){
            arr.push(i+'='+json[i]);
        };
        return arr.join('&');
    }
}

验证

btn.onclick = function(){
    ajax({
        'url':'http://localhost:9102',
        'type':'get',
        'data':{
            user:user.value,
            pass:pass.value
        },
        success:function(data){
            console.log(data)
        }
    })
}

btn.onclick = function(){
    ajax({
        'url':'http://localhost:9102',
        'type':'post',
        'data':{
            user:user.value,
            pass:pass.value
        },
        success:function(data){
            console.log(data)
        }
    })
}

后台内容

var http = require('http');
urlLib = require('url'),
var querystring = require('querystring');
http.createServer(function(req,res){
    res.setHeader('Access-Control-Allow-Origin','*');//允许跨域
    
    //get
    var json = urlLib.parse(req.url,true).query;

    //post
    var str = '';
    req.on('data',function(data){
        str += data;
    });

    req.on('end',function(){
        var json = querystring.parse(str);
        
        res.end();
    });

}).listen(9102);

相关推荐