封装一下,,,用的时候更简单一点:triumph:
其实主要是怕自己以后忘记了
cocos creator 的typescript版本
export class HttpUtil{
private static baseUrl:string = "https://xxx.xxx.xxx/xxxx/";
public static get(url, params:object = {}, callback){
let dataStr = '';
Object.keys(params).forEach(key => {
dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
})
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
}
url = HttpUtil.baseUrl + url;
let xhr = cc.loader.getXMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let response = xhr.responseText;
if (xhr.status >= 200 && xhr.status < 300) {
let httpStatus = xhr.statusText;
callback(true, JSON.parse(response));
}else{
callback(false, response);
}
}
};
xhr.send();
}
//Post请求
public static post(url, param:object = {}, callback){
url = HttpUtil.baseUrl + url;
var xhr = cc.loader.getXMLHttpRequest();
let dataStr = '';
Object.keys(param).forEach(key => {
dataStr += key + '=' + encodeURIComponent(param[key])+ '&';
})
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let response = xhr.responseText;
if (xhr.status >= 200 && xhr.status < 300) {
let httpStatus = xhr.statusText;
callback(true, JSON.parse(response));
}else{
callback(false, response);
}
}
};
xhr.send(dataStr);
}
}
微信小程序版本
let baseUrl = "https://xxx.xxxxx.xxx/xxxx"
function post(url, data, callback) {
wx.request({
url : baseUrl + url,
data,
method: "post",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: res => {
if (typeof (callback) !== "function") return;
callback(res.data);
}
})
}
function get(url, data, callback) {
wx.request({
url: baseUrl + url,
data,
success: res => {
if (typeof (callback) === "function")
callback(res.data);
}
})
}
module.exports = {
post: post,
get:get
}
最新评论