var httpGet = function (url, cbSucc, cbFail, options) {
var flag = false;
var xhr = cc.loader.getXMLHttpRequest();
xhr.open("GET", url);
if (cc.sys.isNative)
xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
var isRaw = false;
if (options && options.responseType) {
isRaw = true;
xhr.responseType = options.responseType;
delete options.responseType;
}
for (var k in options)
if (options.hasOwnProperty(k))
xhr.setRequestHeader(k, options[k]);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (isRaw)
cbSucc(new Uint8Array(xhr.response), xhr);
else
cbSucc(xhr.responseText, xhr);
}
else {
if (!flag) {
flag = true;
cbFail(xhr.statusText, xhr.responseText);
}
}
}
};
xhr.onerror = function () {
if (!flag) {
flag = true;
cbFail(xhr.status, null);
}
};
xhr.send();
};
var httpPost = function (url, data, ajaxSuccess, ajaxError, noBase64, key) {
data = _.isString(data) ? data : JSON.stringify(data);
var xhr = cc.loader.getXMLHttpRequest();
xhr.open("POST", url);
var timedOut = false;
var timer = setTimeout(function(){
timedOut = true;
ajaxError();
xhr.abort();
}, 6000);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// xhr.setRequestHeader("Content-Length", data.length);
xhr.onreadystatechange = function () {
if(timedOut){
return;
}
clearTimeout(timer);
var result, error = false;
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || xhr.status == 0) {
var dataType = xhr.getResponseHeader('content-type');
result = xhr.responseText;
cc.log(result);
try {
if (dataType.indexOf('json')) result = JSON.parse(result);
} catch (e) {
error = e
}
if (error) ajaxError(error, 'parsererror', xhr);
else ajaxSuccess(result, xhr)
} else {
ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr)
}
}
};
xhr.onerror = function () {
ajaxError(xhr.statusText || null);
};
if (noBase64)
xhr.send(data);
else {
xhr.send(Base64.encode(data, key));
}
};
Http请求 cocos2d-js get 和 post
猜你喜欢
转载自blog.csdn.net/W_han__/article/details/102461961
今日推荐
周排行