Ajax的简单封装


function ajax(options){

    // 格式化参数
    var params = formData( options.data );

    // 创建ajax对象
    var xhr = null;
    if( window.XMLHttpRequest ){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // 连接服务器并发送请求
    if( options.type = "GET" ){
        xhr.open( options.type, options.url+"?"+params, options.async );
        xhr.send(null);
    }else if( options.type = "POST" ){
        xhr.open( options.type, options.url, options.async );
        xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" );
        xhr.send(params);
    }

    // 接受返回值,数据处理和展示
    xhr.onreadystatechange = function(){

        if( xhr.readyState == 4 && xhr.status == 200 ){
            options.success( xhr.responseText );
        }

    }

    // function--格式化参数
    function formData(obj){
        var arr = [];
        for( var i in obj ){
            arr.push( i + "=" + obj[i] );
        }

        return arr.join( "&" );
    }

}



// 调用
ajax({

    url: "a.php",
    type: "GET",
    async: true,
    data: {name: "Jenny", age: 18},
    success: function(data){
        console.log( data );
    }

})

a.php:

<?php

    echo $_GET["name"]."===>".$_GET["age"];

?>

输出结果:

Jenny===>18

猜你喜欢

转载自blog.csdn.net/Alex_717/article/details/82118923