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 5 years have passed since last update.

Dartでjsonp

Last updated at Posted at 2014-11-14

はじめに、まず、 Ajaxを呼ぶ先が Acess-Control-Allow-Origin をちゃんと返していれば、こんな凝ったことする必要ない です。

さて、Ajaxで呼べない時のJSONPの取り方。パッケージの中には、下記の2つのように動きそうなライブラリがあるが、動かず。

ちなみに、Dart VMは1.7.2 (2014/11/14)。

さて、困りました。ということで、次のようなコードを発見したのでメモ。(参照sample_jsonp)


import 'dart:html';
import 'dart:js';

void main() {
  querySelector("#button")
      ..text = "Click me!"
      ..onClick.listen(fetchJSON);
}

void fetchJSON(MouseEvent event) {
  context['myCallback'] = (res) {
    print(convert(res));
  };
  ScriptElement script = new Element.tag("script");
  script.src = "https://api.github.com/users/dart-lang/repos?callback=myCallback";
  document.body.children.add(script);
}

convert( JsObject object ) {
  return JSON.decode( context['JSON'].callMethod("stringify", [ object ]));
}

ちょっと解説。

("#button")のクリックする度にデータを取得しに行っている。

contextというのは、Dart内でJSでの変数を参照する時に使うもの。このコードではmyCallback =以降の関数をアサインしている。
その次の後の行で<script>タグを作りだして、そのsrcにJSONPで呼ぶべきURLを渡している。

そして、ajaxで得たJsObjectをDartの文字列に変換するのにもcontextから、JSのJSON.stringigy()を呼び出している。

ふむふむ。なんとも苦肉の策。

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?