KITASENJU DESIGN BLOG

memo, html, javascript, unity

JsonLoader.ts

export class JsonLoader {
    load(url: string, callback: (data: any) => void, errorCallback?: (error: any) => void) {
        const xhr = new XMLHttpRequest();

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) { // 4 means the request is done.
                if (xhr.status === 200) { // 200 means successfully received response.
                    try {
                        const jsonData = JSON.parse(xhr.responseText);
                        callback(jsonData);
                    } catch (e) {
                        errorCallback && errorCallback(`Failed to parse JSON: ${e}`);
                    }
                } else {
                    errorCallback && errorCallback(`HTTP Error: ${xhr.status}`);
                }
            }
        };

        xhr.open("GET", url, true);
        xhr.send();
    }
}

"FOOTER"