Help us understand the problem. What is going on with this article?

とりあえず Promise な XMLHttpRequest したい時に書くコード

More than 1 year has passed since last update.
  • ブラウザの開発コンソールとかでとりあえず ajax なことしたい時に使う
  • とりあえず get のみ。post は内容をちょっと変えればできる
  • cors は何もしてないので実行したいページに行って実行してください(例の場合なら yahoo のページへ行って実行する)
(() => {
    const getUrl = (url) => {
        return new Promise((resolve, reject) => {
            const req = new XMLHttpRequest();
            req.open('get', url, true);
            req.responseType = 'document';
            req.onload = () => {
                if (req.status === 200) {
                    resolve(req.response);
                } else {
                    reject(new Error(req.statusText));
                }
            };
            req.onerror = () => {
                reject(new Error(req.statusText));
            }
            req.send();
        });
    };

    getUrl('https://www.yahoo.co.jp')
    .then((response) => {
        console.log('success', response);
    })
    .catch((response) => {
        console.log('failed.', response);
    });
})();

参考

JavaScript Promiseの本
http://azu.github.io/promises-book/

XMLHttpRequestで取得したHTMLにDOMでアクセスしたい
https://qiita.com/yuki549/items/9f5ed466e3687cb7de8e

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away