2012年11月3日土曜日

開発環境

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

その他参考書籍

15-1.

コード(TextWrangler)

var xmlhttp = new XMLHttpRequest();
var drink = encodeURIComponent(document.getElementById('drink').value);
var url = "recipe.php?drink=" + drink;
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = printRecipe;
xmlhttp.send(null);

function printRecipe(o){
  if(xmlhttp.readySate === 4 && xmlhttp.status === 200){
    var body = document.getElementsByTagName("body")[0];
    var recipe = document.createElement("div");
    var h3 = document.createElement("h3");
    var title = xmlhttp.responseXML.getElementsByTagName('title')[0].firstChild.nodeValue;
    title = document.createTextNode(title);
    h3.appendChild(title);
    recipe.appendChild(h3);
    var ul = document.createElement('ul');
    var ingredients = xmlhttp.responseXML.getElementsByTagName("ingredient");
    for(var i = 0; i < ingredients.length; i++){
      var li = document.createElement("li");
      var ingredient = ingredients[i].firstChild.nodeValue;
      ingredient = document.createTextNode(ingredient);
      li.appendChild(ingredient);
      ul.appendChild(li);
    }
    recipe.appendChild(ul);
    var p = document.createElement("p");
    var instruction = xmlhttp.responseXML.getElementsByTagName("instruction")[0].firstChild.nodeValue;
    instruction = document.createTextNode(instruction);
    p.appendChild(instruction);
    recipe.appendChild(p);
    body.appendChild(recipe);
  }
}

0 コメント:

コメントを投稿