美文网首页Cocos Creator
Cocos creator 原生平台上 下载远程文本文件

Cocos creator 原生平台上 下载远程文本文件

作者: 洒一地阳光_217d | 来源:发表于2019-02-21 22:34 被阅读2次

本篇文章介绍的是在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");
    },

相关文章

网友评论

    本文标题:Cocos creator 原生平台上 下载远程文本文件

    本文链接:https://www.haomeiwen.com/subject/jfsjyqtx.html