2012年11月2日金曜日

開発環境

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

その他参考書籍

14-5.

コード(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 text = xmlhttp.responseText;
    var recipe = document.getElementById('recipe');
    recipe.innerHTML(text);
  } else {
    alert("エラー発生");
  }
}

jQueryを使った場合。

コード(TextWrangler)

var drink = $('#drink').val();
var options = {
  type: 'GET',
  url: "recipe.php?q =" + drink,
  dataType: "html",
  success: function(data, textStatus){
    $('#recipe').text(data);
  },
  error: function(){
    $('#recipe').text("エラー発生");
  },
  // 成功の有無に関わらず最後に実行される
  complete: function(){
     // 処理内容
  }
};
$.ajax(options);

0 コメント:

コメントを投稿