LoginSignup
3
4

More than 5 years have passed since last update.

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

Posted at
  • ブラウザの開発コンソールとかでとりあえず 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

3
4
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
3
4