Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created August 18, 2012 02:15
Show Gist options
  • Select an option

  • Save s-hiroshi/3383936 to your computer and use it in GitHub Desktop.

Select an option

Save s-hiroshi/3383936 to your computer and use it in GitHub Desktop.
JavaScript > json padding simple sample
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JSON Padding</title>
<script>
function doJSONP(text, callback) {
var text = (text) || 'Foo',
callback = (callback) || 'callback',
target = document.createElement('script');
target.charset = 'utf-8';
// JSONPの利点は異なるドメインのスクリプトを呼び出せる点にあるが
// 今回は同一サーバーjsonp.phpを呼び出す。
target.src = 'jsonp.php?text=' + text + '&callback=' + callback;
// JSONP実行(スクリプトタグ出力)
document.body.appendChild(target);
window[callback] = function(data) {
document.getElementById('results').innerHTML = data.text;
};
}
</script>
</head>
<body>
<div id="results"></div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<script>doJSONP('Bar', 'myCallback');</script>
</body>
</html>
<?php
$text = htmlspecialchars($_GET['text'], ENT_QUOTES);
$callback = htmlspecialchars($_GET['callback'], ENT_QUOTES);
print <<<EOF
{$callback}({
text: '{$text}' + ', Hello'
});
EOF;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment