2013年11月19日火曜日

開発環境

『初めてのJavaScript 第2版』(シェリー・パワーズ著(Shelley Powers著)、武舎 広幸+武舎 るみ訳、オライリージャパン、2009年、ISBN978-4-87311-425-5) の15章(Ajaxのデータ - XMLかJSONか)、練習問第15-2.をDartで解いてみる。

その他参考書籍

練習問第15-2.

dart:json libraryは無くなって、dart:convertのJSONに移動したっぽい。

コード

sample.dart

import 'dart:html';
import 'dart:convert' as convert;

void main(){
  Element run = querySelector('#run'),
          clear = querySelector('#clear'),
          div = querySelector('#d0');
  run.onClick.listen((MouseEvent event){
    div.text = '';
    String result = '${window.navigator.userAgent}\n';
    String url = 'http://mkamimura.com/kamimura_blog/learning_javascript/sample1.json';
    HttpRequest.getString(url).then((String string){
      Map recipe = convert.JSON.decode(string);
      Element title = new Element.tag('h3');
      title.text = recipe['title'];
      List<Map<String, String>> ingredients = recipe['ingredients'];
      Element ul = new Element.tag('ul');
      ingredients.forEach((Map<String, String> ingredient){
        Element li = new Element.tag('li');
        li.text = ingredient['ingredient'];
        ul.append(li);
      });
      Element instruction =new Element.tag('p');
      instruction.text = recipe['instruction'];
      [title, ul, instruction].forEach((Element e) => div.append(e));
    }).catchError((e){
      div.text = '取得失敗: $e';
    });
      
  });
  clear.onClick.listen((MouseEvent event) => div.text = '');
}

0 コメント:

コメントを投稿