//封装一个ajax函数

  // 参数约定:
    // url  必须
    // method 可选, 默认是 get
    // data 可选, 可以是字符串, 也可以是对象( 键值对 )
    // fn 处理响应回来的数据, 函数需要有参数, 即响应回来的数据

function ajax( options ){
    //定义参数
   var url=options.url,
        method=options.method || "GET",
        data=options.data || null,
        fn=options.fn || null

    //首先转换data参数
    var tmp=[];
    //如果传入的是字符串,不需要处理,如果传入的是一个键值对,转换成字符串
    if(data != null && typeof data =="object"){
        for( var k in data){
            tmp.push(k + "=" + data[k] );
        }
        data=tmp.join("&");
    }

    //开始发送ajax请求
    var xhr=new XMLHttpRequest();
    xhr.open(method,url);
    //如果请求方式是post  设置头
    if( method.toLowerCase() == "post"){
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    }
    xhr.onreadystatechange=function(){
        if( xhr.readyState===4 && xhr.status==200){
            if(typeof fn =="function"){
                fn( xhr.responseText );
            }
        }
    };
    xhr.send(data);
};

欢迎留言