Chapter 18. Communication
■18.0 Introduction
Ajaxは比較的簡単なステップで行われる- サーバーサイドで呼び出すAPIを準備する
- APIをJavaScriptから呼ぶ
- その結果を処理する
■18.1 Accessing the XMLHttpRequest Object
XMLHttpRequestオブジェクトの以下のメソッドが挙げられる- open
- setRequestHeader
- send
- sendAsBinary
- abort
- getResponseHeader
■18.2 Preparing the Data for Transmission
データ送信のためにする準備encodeURIComponentで文字列をエスケープするとスペースもエスケープされ、意図したものとは違う事になる場合もある。
function postEncodeURIComponent(str) {
str=encodeURIComponent(str);
return str.replace(/%20/g,"+");
}
■18.5 Checking for an Error Condition
Ajaxのエラーハンドリング
// xmlhttp.onreadystatechange=processResult;
function processResult() {
if (http.readyState == 4 && http.status == 200) {
document.getElementById("result").innerHTML=http.responseText;
} else {
alert(http.statusText);
}
}
まあ、良くある感じだけどブラウザでバグが存在するので、jQueryあたりの参考にすると成功してるのにstatusが200以外の時もあるのが分かったりする。■18.7 Making an Ajax Request to Another Domain (Using JSONP)
JSONPについて。
function addScript( url) {
var script = document.createElement('script');
script.type="text/javascript";
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
上記のようなコーでコールバックを指定して使いますが、JSONPはセキュリティ的な懸念を持っているのでできるだけ使うのを止めときましょう。プロキシアプリを経由するなどしてクロスドメインを突破する方法を考えるべき。
■18.9 Using a Timer to Automatically Update the Page with Fresh Data
下のような処理をtimerで定期的に行う事で、自動でアップデートするという話。
function processResponse() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var li = document.createElement("li");
var txt = document.createTextNode(xmlhttp.responseText);
li.appendChild(txt);
document.getElementById("update").appendChild(li);
} else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
alert(xmlhttp.responseText);
}
}
関連の話でCometやWebsocketやlong pollingがある。(書いてないけど Server-Sent EventsもこてさきAjax:HTTPで、サーバーPushサービス Server-Sent Events - livedoor Blog(ブログ))WebSocketだとonmessageでデータを受け取る毎に処理する事でサーバーの更新を直ぐに反映できる。
if ("WebSocket" in window) {
var ws = new WebSocket("ws://example.com/service");
ws.onopen = function() {
// Web Socket is connected. You can send data by send() method.
ws.send("message to send"); ....
};
ws.onmessage = function (evt) { var received_msg = evt.data; ... };
ws.onclose = function() { // websocket is closed. };
} else {
// the browser doesn't support WebSocket.
}
■18.10 Communicating Across Windows with PostMessage
本題のPostMessage。ウィジェットのようにiframe内にあるものとコミュニケーションをするにはどうするか。
データを送るsenderページとデータを受け取るListenerページがあって、
まずListenerページにmessageイベントハンドラを設定する。
messageイベントが起きたらreceive関数で処理する。
addEvent(window,"message",receive);// messageイベントハンドラ
function receive(e) {
var img = document.getElementById("image");
img.src = e.data.split(",")[0];
img.alt = e.data.split(",")[1];
e.source.postMessage("Received " + e.data, "http://burningbird.net");
}
そして、senderページからpostMessageメソッドを使ってデータを送りつける。window.postMessage - MDC
function sendMessage() {
try {
var farAwayWindow = document.getElementById("widgetId").contentWindow;
farAwayWindow.postMessage(
"dragonfly6.thumbnail.jpg,Dragonfly on flower",
'http://burningbird.net');
} catch (e) {
alert(e);
}
};
postMessageはクロスドメインを超えた範囲で通信が行えるので、receive側は必ずe.origin あるいは e.source プロパティでどこから送られてきたのかを確認する必要がある。
function receive(e) {
if (e.origin == "http://jscb.burningbird.net"){//来た場所をチェック
alert(e.data);
}
}
JavaScriptでの通信の確認的な章コメント(0件)
- TB-URL http://efcl.info/adiary/081/tb/