More Related Content
Similar to いまさら聞けないJSONPのまとめ (19)
More from Yujiro Araki (9)
いまさら聞けないJSONPのまとめ
- 9. <script>
function showPrice(data) {
alert("Name: " + data.name + ", Price: " + data.price);
}
showPrice({ name: 'foo', price: 3000 });
</script>
index.html
JSONPの利用(1/5)
JSONPによるクロスドメインの通信: 第1回 JSONPとjQueryを組み合わせ、強力なマッシュアップを迅速に作成する
http://www.ibm.com/developerworks/jp/web/library/wa-aj-jsonp1/
- 12. <script>
function showPrice(data) {
alert("Name: " + data.name + ", Price: " + data.price);
}
</script>
<script src="http://user-domain/show.js"></script>
showPrice({ name: 'foo', price: 3000 });
show.js
index.html
この部分を動的生成にする
JSONPの利用(4/5:動的生成)
動的生成にする理由:イベント発生契機に通信を行いたい場合
- 13. <script>
function showPrice(data) {
alert("Name: " + data.name + ", Price: " + data.price);
}
function show() {
var script = document.createElement('script');
script.src = 'http://user-domain/show.js';
(document.getElementsByTagName('head'))[0].appendChild(script);
}
</script>
<a href="#" onclick="show() return false;">click</a>
index.html
show.js
showPrice ({ name: 'foo', price: 3000 });
JSONPの利用(5/5:動的生成)
- 14. <script>
function callback(data) {
alert("Name: " + data.name + ", Price: " + data.price);
}
function show() {
var script = document.createElement('script');
script.src = 'http://user-domain/show.php?jsonp=callback;
(document.getElementsByTagName('head'))[0].appendChild(script);
}
</script>
<a href="#" onclick="show() return false;">click</a>
<?php
echo $_GET['jsonp'] . "({ name: 'foo', price: 3000 });";
?>
show.php(他サーバ)
index.html
クエリーパラメータ「jsonp」の値をコールバック関数名として設定
関数のパラメータにJSONを設定
JSONPの実用的な実装例
- 17. <script>
$.getJSON("http://user-domain/hoge.php?&callback=?",
function(data) {
$('div').html(data.title + data.description);
});
</script>
クエリーパラメータ「callback(名称は何でもよい)」の値に
「?」を設定することでJSONPリクエストとして扱われる。
「?」の部分はjQueryで自動生成
実際のHTTPリクエスト:
http://user-domain/hoge.php?callback
= jQuery17208957796988929256_1334645135858&_=1334645136039
<?php
echo $_GET['jsonp'] . '(' . "{ title: 'foo', description: 'bar' }" . ');';
?>
hoge.php
実行される
関数
最後の“_=[TIMESTAMP]“はキャッシュを無効にするためのもの http://api.jquery.com/jQuery.ajax/
$.ajaxでのみ有効な模様
jQueryによるAjax+JSONPのサポート:$getJSON