Cocos Creator网络请求

本文介绍了一个使用JavaScript封装的网络请求模块,包括GET和POST两种请求方式。该模块通过XMLHttpRequest实现,能够处理请求参数的拼接,并能解析响应数据为JSON格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var appScript = {
    ip: "https://game.zuiqiangyingyu.net/wb",
    version: "1.0.0",   

    Get: function(url,reqData,callback){
        var self = this;

        url += "?";
        for(var item in reqData){
            url += item +"=" +reqData[item] +"&";
        }
        // console.log(self.ip + url)
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4){
                if(xhr.status >= 200 && xhr.status < 400){
                    var response = xhr.responseText;
                    // console.log(response)
                    if(response){
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    }else{
                        console.log("返回数据不存在")
                        callback(false);
                    }
                }else{
                    console.log("请求失败")
                    callback(false);
                }
            }
        };
        xhr.open("GET", self.ip + url, true);
        xhr.send();
    },

    Post: function (url, reqData, callback) {
        var self = this;
        // console.log(url)
        // console.log(reqData)
        //1.拼接请求参数
        var param = "";
        for(var item in reqData){
            param += item + "=" + reqData[item] + "&";
        }
        //2.发起请求
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4){
                if(xhr.status >= 200 && xhr.status < 400){
                    var response = xhr.responseText;
                    // console.log(response)
                    if(response){
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    }else{
                        console.log("返回数据不存在")
                        callback(false);
                    }
                }else{
                    console.log("请求失败")
                    callback(false);
                }
            }
        };
        xhr.open("POST", self.ip + url, true);
        xhr.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");  
        xhr.send(param);//reqData为字符串形式: "key=value"
    },


};

module.exports = appScript;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值