Open Source Web Development Tutorials - Dev Shed
Google AjaxライブラリAPIを使おう
(2009/02/23公開)
Google APIのバージョニング
例によって、Google APIのバージョニングは非常に簡単で、前に示した適切なload()メソッドを呼び出すときに、JavaScriptライブラリのどのバージョンをダウンロードするかを指定するだけで済む。
このプロセスがどのように機能するかをもっと明確に理解できるように、前のページで作成したAjax駆動型プログラムを書き直したものを下に示してある。ここでは、バージョニング機能を使用して、Prototype 1.6を使用するように指定した。この場合のコードは次のようになる。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Reading file contents with Prototype library (uses Google API)</title>
<style type="text/css">
body{
padding: 0;
margin: 0;
background: #fff;
}
h1{
font: bold 18pt Arial, Helvetica, sans-serif;
color: #000;
}
#filecontents{
width: 600px;
padding: 10px;
border: 1px solid #999;
font: normal 10pt Arial, Helvetica, sans-serif;
color: #000;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
// load Prototype library with Google API
google.load("prototype", "1.6");
// read file contents with Ajax
function readFileContents(){
// send http request
var ajaxobj=new Ajax.Request('read_file.php',{method: 'get',onComplete: displayFileContents,onFailure: displayError});
}
// display file contents
function displayFileContents(requestObj){
$('filecontents').innerHTML=requestObj.responseText;
}
// display error message
function displayError(requestObj){
$('filecontents').innerHTML='Error reading file contents!';
}
// initialize file reading application
function initializeApplication(){
// attach click handler to HTML button
Event.observe('btn','click',readFileContents);
}
google.setOnLoadCallback(initializeApplication);
</script>
</head>
<body>
<h1>Reading File Contents with Prototype library (uses Google API)</h1>
<p><input type="button" id="btn" value="Read File Now!" /></p>
<div id="filecontents"></div>
</body>
</html>
Google APIを使用するときに、JavaScriptフレームワークの特定のバージョンを非常に簡単に使用できることがお分かりいただけただろうか?お分かりのように、このプロセスで必要なことは、使用するライブラリの正確なバージョンを指定して、メソッドを呼び出すことだけだ。ただ、それだけだ。
この最後の例で、GoogleのJavaScriptライブラリAPIの基本的な紹介を終わることにしよう。いつものように、この記事で取り上げたサンプルコードは、すべて自由にいじってもらって結構だ。そうすれば、独自のクライアントサイドWebアプリケーション を作成するときの、このAPIの使い方がさらによく理解できるだろう。
まとめ
この連載のこの第1回では、Prototypeフレームワークのローカルコピーを使用するのではなく、GoogleのAjaxライブラリAPIを使用してダウンロードする方法を説明した。読者のWebのホスティングサービスへ負荷が大きい場合は特に、このGoogleベースのアプローチは非常に魅力的で、あなたが作成したJavaScriptファイルをGoogleのサーバーから直接配信したいと思うだろう。
次回は、GoogleのAPIを通じてjQuery JavaScriptライブラリを使用する方法を説明したいと思う。このパッケージを使用してクライアントサイドアプリケーションを開発している人には、きっと役に立つと思う。
次のチュートリアルに、こうご期待!
Copyright © 2008 Ziff Davis Enterprise, Inc.
Originally appearing in the U.S. Edition of Dev Shed. All Rights Reserved.








