本篇文章介绍的是在Cocos Creator中,如何使用XMLHttpRequest下载远程文本文件(如.txt文件)
请看代码
//需要解码。uft8和unicode的解码方式不同,ansi的暂时不支持
loadRemoteTxtFile(url, callback, caller, readAsUtf8 = true) {
if (url == null || url == "") {
return;
}
if (window.jsb == null) {
callback.call(caller, null);
return
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("loadRemoteTxt ok");
let ab = xhr.response;
let content = null;
if (readAsUtf8) {
content = String.fromCharCode.apply(null, new Uint8Array(ab));
} else {
content = String.fromCharCode.apply(null, new Uint16Array(ab));
}
callback.call(caller, content);
} else {
callback.call(caller, null);
}
} else {
callback.call(caller, null);
}
}.bind(this);
//responseType一定要在外面设置
xhr.responseType = 'arraybuffer';
xhr.open("GET", url, true);
xhr.send();
debug.log("xhr.send");
},
网友评论