開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Safari、Firefox + Firebug (Webプラウザ、プラグイン)
- JavaScript (プログラミング言語)
- jQuery (JavaScript Library)
Head First JavaScript ―頭とからだで覚えるJavaScriptの基本( Michael Morrison (著), 豊福 剛 (翻訳)、オライリージャパン)の12章(ダイナミックなデータ)、自分で考えてみよう(p.567)を解いてみる。
その他参考書籍
自分で考えてみよう(p.567)
コード(BBEdit)
ajax.js
var Blog = function (date, body, image) {
this.date = date || new Date();
this.body = body || 'Nothing going on today';
this.image = image;
},
AjaxRequest = function () {
this.request = null;
if (window.XMLHttpRequest) {
try {
this.request = new XMLHttpRequest();
} catch (e) {
this.request = null;
}
} else if (window.ActiveXObject) {
try {
this.request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
this.request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
this.request = null;
}
}
}
},
pre = document.getElementById('pre0'),
ajax_req,
url = 'http://mkamimura.com/kamimura_blog/javascript/' +
'head_first_javascript/blog.xml',
getText = function (elem) {
var text = '',
i,
max,
child,
value,
nodes;
if (elem) {
if (elem.childNodes) {
for (i = 0, max = elem.childNodes.length; i < max; i += 1) {
child = elem.childNodes[i];
value = child.nodeValue;
if (value) {
text += value;
} else {
nodes = child.childNodes;
if (nodes) {
value = nodes[0].nodeValue;
if (value) {
text += value;
}
}
}
}
}
}
return text;
},
handler = function () {
var xml_data,
blog,
author;
if (ajax_req.getReadyState() === 4 && ajax_req.getStatus() === 200) {
xml_data = ajax_req.getResponseXML();
blog = xml_data.getElementsByTagName('blog')[0];
author = blog.getElementsByTagName('author')[0];
// ブログの署名をXMLのauthorタグに格納された名前で設定
Blog.prototype.signature = getText(author);
pre.innerHTML = Blog.showSignature();
}
};
Blog.showSignature = function () {
return 'This blog created by ' + Blog.prototype.signature;
};
AjaxRequest.prototype.send = function (type, url, handler, post_data_type, post_data) {
if(this.request !== null) {
this.request.abort();
url += "?dummy=" + new Date().getTime();
try {
this.request.onreadystatechange = handler;
this.request.open(type, url, true);
if (type.toLowerCase() === 'get') {
this.request.send(null);
} else {
this.request.setRequestHeader('Content-Type', poast_data_type);
this.request.send(post_data);
}
} catch (e) {
alert('サーバとの通信でAjaxエラー\n' + '詳細: ' + e);
}
}
};
AjaxRequest.prototype.getReadyState = function () {
return this.request.readyState;
};
AjaxRequest.prototype.getStatus = function () {
return this.request.status;
};
AjaxRequest.prototype.getResponseXML = function () {
return this.request.responseXML;
};
ajax_req = new AjaxRequest();
ajax_req.send('GET', url, handler);
0 コメント:
コメントを投稿