1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AlphabetAdvent Calendar 2022

Day 24

【X】XMLHttpRequestを何も考えずに使いたい

Last updated at Posted at 2022-12-23

外部ファイルを持ってきたいとき〜!!

結論

これをベースにすればだいたいなんとかなる

let url = "https://example.com/"
let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "document"; // text, arraybuffer, blob, document, jsonが使用可能。jsonのresponseは自動パースされる
xhr.send();

xhr.onload = () => {
    if (xhr.status != 200) {
        console.log("取得に失敗");
    } else {
        /* やるべき処理 */
        /* xhr.responseにレスポンス文が入ってます */
    }
};

better

Fetchがあるぞ

let url = "https://example.com/"
let response = await fetch(url);

if (response.ok) {
    /* やるべき処理 */
    /* 例えばjsonとしてとりたいなら"responce.json()"を変数にぶち込みます */
} else {
    console.log("取得に失敗");
}

responseに何が入っているかはここらへんを見るといいと思います

blobを取りたいならResponse.blob()、テキストを取りたいならResponse.text()みたいな感じ。
一度Response.blob()などをするともう一度書き出したりはできないらしいです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?