cocos creator如何实现网络请求http之封装

摘要
cocos creator http请求。在 Cocos Creator 中,我们使用的标准网络接口:
XMLHttpRequest:用于短连接
WebSocket:用于长连接
今天我们说一下短连接的封装。

环境
cocos Creator 引擎2.4.3
编辑工具HBuild X

最终效果
体验一下
在这里插入图片描述
效果图如下,我们获取一个抽奖列表,展示
在这里插入图片描述

在这里插入图片描述

简单示例

	let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
     if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
         var response = xhr.responseText;
         console.log(response);
     }
 };
 xhr.open("GET", url, true);
 xhr.send();

开发者可以直接使用 new XMLHttpRequest() 来创建一个连接对象。

上面的代码并没有封装,下面我们来将代码封一下

封装代码

//短链接请求
cc.http = function(options) {
	return new Promise((resolve, reject) => {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
				var res = JSON.parse(xhr.responseText);
				resolve(res);
			}
		};
		xhr.timeout = options.timeout || 50000; // 5 seconds for timeout
		var method = options.method || 'GET';
		var url = options.url;
		options.data = options.data || {};
		if (method == 'get' || method == "GET") {
			var url = options.url + '?' + cc.vv.keyObject(options.data);
			xhr.open(method, url, true);
			xhr.send();
		} else {
			xhr.open(method, options.url, true);
			xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
			xhr.send(JSON.stringify(options.data));
		}
	});
};

上面的封装代码满足get,post的请求

结语:
欢迎加入微信群一起学习讨论!
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值