Open Source Web Development Tutorials - Dev Shed
jQueryフレームワークとGoogleのAjaxライブラリAPIを併用する
(2009/03/02公開)
復習-Google APIを通じてJavaScriptライブラリをダウンロードする
Google APIを通じてjQueryライブラリをダウンロードして使用する方法を説明するにあたって、前回に示した実例を再掲しておく。この例は、Prototypeパッケージを使用した場合と同じプロセスを実行する方法を示している。
その例は、大体、次のようだったと思う。
<!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.4");
// 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を使用することにより、いかに簡単にPrototypeライブラリの指定したバージョンをダウンロードできるかを如実に示している。この例では、google.load()メソッドによって明示的にライブラリの依存関係がロードされ、Webサーバーからテキストファイルの内容をフェッチする簡単なAjaxプログラムの構築に使用されている。
また、指定したコールバック関数を実行するために、プログラムの終わりに追加されているgoogle.setOnLoadCallback()メソッドが、どのように使用されているかも、お分かりいただけるだろう。とても分かりやすいだろう。
ここで、Google APIを使用して、Prototypeフレームワークをダウンロードして使用する方法を思い出してほしい。ところで、次は何?そうだね、「はじめに」のところで説明したように、このAPIは、jQueryライブラリなど、ほかのJavaScriptパッケージもサポートしている。
次のセクションでは、GoogleのAPIを利用して、このライブラリを使用する方法を詳細に説明することにしよう。
次ページへのリンクをクリックして、この先を読んでほしい。
Copyright © 2008 Ziff Davis Enterprise, Inc.
Originally appearing in the U.S. Edition of Dev Shed. All Rights Reserved.








