LoginSignup
3
0

More than 5 years have passed since last update.

javascript コンソール画面でXMLHttpRequest(XHR)通信してみた

Posted at
  • javascriptのコンソール画面でxhr通信をしたかったので、やったついでにメモしておく
  • console.logで出力できるやり方は結構載ってたが、変数に入れるやり方があまり見つからなかった
  • 今回はgoogle books apiを叩いてみた。任意のisbnを入れればjsonがhogeに返ってくる
main.js
function getHttpRequest(url, c){
    // インスタンス作成
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        // 処理が成功したらresponseTextをコールバック
        if(xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300){
            c(JSON.parse(xhr.responseText));
        }
    }
    var method = "GET";
    xhr.open(method, url);
    xhr.send();
}
// 任意のisbn
var isbn = *******;
// google booksのgetエンドポイント
var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:"+isbn;
// 変数にjsonを入れたい時. console.log(res)で出力してもよし
var hoge;
getHttpRequest(url, function(res){
    hoge = res['items'][0];
})

hoge.volumeInfo.titleとかすると書籍名が取れたりする

  • 実はfetchの方が良かったかもっていう。。。
3
0
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
0