LoginSignup
1
0

More than 3 years have passed since last update.

コールバック関数&jQuery不要「JSONP」取得関数(webページで複数回JSONPを使いたい人に)

Last updated at Posted at 2020-06-26

Google Apps Scriptで作った複数のAPIからのJSONP取得が面倒(コールバック関数をその分だけ用意する必要があるなど)かつjQuery拡張のjQuery-JSONPを使いたくなかったので、コールバック関数無しにJSONPからJSONを取得する関数をピュアなJavaScriptで作ってみました。この関数を使えば、もう、JSONP取得のためにわざわざコールバック関数を用意する必要はありません。

大元のコード

JavaScript
//引数
//url: jsonpのurl
//cbName: jsonpを起動することになっているはずのコールバック関数の名前
function JSONP(url, cbName="callback") {
    return new Promise(function(_r, _e) {
        window[cbName] = function(j) {
            delete window[cbName];
            _r(j);
        }
        var s = document.createElement("script");
        s.src = url;
        document.head.appendChild(s);
        s.onerror = function(e) {
            delete window[cbName];
            _e(e);
            s.remove();
        }
    });
}

minified版

JavaScript
function JSONP(url,cbName="callback"){return new Promise(function(i,r){window[cbName]=function(n){delete window[cbName];i(n)};var u=document.createElement("script");u.src=url;document.head.appendChild(u);u.onerror=function(n){delete window[cbName];r(n);u.remove()}})}

使い方

JSONP関数はPromiseオブジェクトを返すので、返り値はthenで受けます。

分からない方のために念の為補足すると、thenの中に書かれた処理は、JSONPからJSONを取得した「直後」に起動します。

JSONPのURL

JavaScript
var url = "https://script.google.com/macros/s/XXXXX/exec?callback=cbFunc";
//この例では、"cbFunc"がリクエストしたコールバック関数名
//サーバー側でコールバック関数名が指定されている(ヒエッ…)場合は、その名前を把握しておく

使い方

JavaScript
/*使用例その1*/
JSONP(url, "cbFunc")
.then(function(r) {//jsonp読み込み成功時の処理
    console.log(r);//返り値(r)はJSONオブジェクト
})
JavaScript
/*使用例その2*/
JSONP(url, "cbFunc")
.then(function(r) {
    console.log(r);
})
.catch(function(e) {//jsonp読み込み失敗時の処理
  console.log(e);//返り値(e)はonerrorのイベントオブジェクト
})
JavaScript
/*使用例その3-α*/
//コールバック関数名は被らないように
JSONP(url, "cbFunc")
.then(function(r) {
    console.log(r);

    JSONP(url, "cbFunc")
    .then(function(r) {
        console.log(r);
    })
})

/*使用例その3-β*/
//IEを気にする必要が無いなら、アロー関数を使うのもアリ
JSONP(url, "cbFunc").then(r=>console.log(r),JSONP(url, "cbFunc_2").then(r=>console.log(r)));
1
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
1
0