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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值