因为以前往微信和抖音发布小游戏时,里面用了大量的wx.request这样的接口做http请求,现在需要往原生平台发布了,没法用wx.request接口了,但为了尽量少改动代码,所以想把cocos creator的http请求,就是getXMLHttpRequest这东西封装的尽量和wx.request的调用格式一样,就像下面这种调用方法
wx.request({
url: “myUrl”,
data: {
data1: “”,
data2: “”,
},
success: (res) => {
console.log(res);
},
fail: (res) => {
console.log(res);
},
complete: (res) => {
console.log(res);
},
})
从网上找了个cocos creator的http请求封装的代码,虽然用起来也没问题,但还是感觉没有wx.request这种格式调用起来方便,下面是网上找的代码
var httpUtils = cc.Class({
extends: cc.Component,
properties: {
},
statics: {
instance: null
},
// use this for initialization
onLoad: function () {
},
httpGets: function (url, callback) {
var xhr = cc.loader.getXMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
var respone = xhr.responseText;
callback(respone);
}
};
xhr.open("GET", url, true);
if (cc.sys.isNative) {
xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
}
// note: In Internet Explorer, the timeout property may be set only after calling the open()
// method and before calling the send() method.
xhr.timeout = 5000;// 5 seconds for timeout
xhr.send();
},
httpPost: function (url, params, callback) {
var xhr = cc.loader.getXMLHttpRequest();
xhr.onreadystatechange = function () {
cc.log('xhr.readyState=' + xhr.readyState + ' xhr.status=' + xhr.status);
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
var respone = xhr.responseText;
callback(respone);
} else {
callback(-1);
}
};
xhr.open("POST", url, true);
if (cc.sys.isNative) {
xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
}
// note: In Internet Explorer, the timeout property may be set only after calling the open()
// method and before calling the send() method.
xhr.timeout = 5000;// 5 seconds for timeout
xhr.send(params);
}
});
httpUtils.getInstance = function () {
if (httpUtils.instance == null) {
httpUtils.instance = new httpUtils();
}
return httpUtils.instance;
};
个人理解,肯定是把里面的httpPost方法稍微改动一下,重新封装个request方法(就是可以指定url和data参数,然后有回调的success、fail、complete)就可以了,但无奈本人javascript功力实在欠缺,自己封装不好,如果哪位老师有时间,能帮忙封装一下吗?或者用伪代码的方式指点一下也可以。我知道,这个httpPost方法直接用也算比较方便,也没问题,无奈就是还是不如和wx.request一模一样更方便。唉,最近脑子越来越不好使了,这问题显然是伸手党了。如果各位老师不嫌弃的话,请多多指教,万分感谢!