js 模拟get / post 请求及返回值处理

话不多说,直接上代码,复制粘贴,把URL改成自己想访问的,即可使用

httpGetTest();
httpPostTest();

//get请求
function httpGetTest() {
    var url = 'http://XXX/XXXApi';
    console.log('start===>XMLHttpRequest');
    var xhr = new XMLHttpRequest();
    xhr.responseType = "text";
    xhr.open('GET', url);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;")
    xhr.send();
    xhr.onload = function(e) {
        console.log('onload。e====>' + JSON.stringify(e));
    };
    xhr.onreadystatechange = function(e) {
        console.log('onreadystatechange。e====>' + JSON.stringify(e));
        if(xhr.readyState == 4 && xhr.status == 200){
            var xhrRes = xhr.responseText;
            console.log('return message====>' + xhrRes);
        }
    };
}

//post请求
function httpPostTest() {
    var url = 'http://XXX/XXXApi?module=httpPostTest';
    var xhr = new XMLHttpRequest();
    xhr.responseType = "text";
    xhr.open('POST', url);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    //1. 发送 formData
    var formData = new FormData();
    formData.append("username", "Anne");
    formData.append("accountnum", 123456);
    xhr.send(formData);

    //2. 发送 JSON
    // xhr.send({"username": "Anne"});

    //3. 发送 字符串
    // xhr.send(JSON.stringify({"username": "Anne"}));

    xhr.onload = function(e) {
        console.log('httpPostTest onload。e====>' + JSON.stringify(e));
    };
    xhr.onreadystatechange = function(e) {
        console.log('httpPostTest onreadystatechange。e====>' + JSON.stringify(e));
        if(xhr.readyState == 4 && xhr.status == 200){
            var xhrRes = xhr.responseText;
            console.log('httpPostTest return message====>' + xhrRes);
            //正常情况下收到返回值 {"status": 1, "res": "http post test return!"}
        }
    };
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值