呼び出し側
呼び出し側のページからは、jQuery で ajax
jQueryのロード
Google Libraries APIから拝借。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
HTMLのサンプル
CGIのファイル名は適宜変更ください。POSTでもGETでもお好きにど~ぞ♪
<input type="text" id="longUrl">
<input type="text" id="shortUrl">
<input type="button" id="shorten" value="短縮">
<script type="text/javascript">
$.("#shorten").click(function() {
$.("#shortUrl").val("取得中…");
$.ajax({
type: "POST", // GETでもok!CGIに合わせて。
url: "shortener.cgi", // CGIに合わせて。
data: { longUrl: $.("#longUrl") }, // CGIに合わせて。
dataType: "json", // パススルーで!
success: function(data, textStatus, jqXHR) {
if (data.id) {
$.("#shortUrl").val(data.id);
}
},
error: function(jqXHR, textStatus, errorThrown) {
$.("#shortUrl").val("エラーだよ!");
}
});
});
</script>ハマリポイント
↓こんな感じでPOSTできればいいんですが、クロスドメインだとGETに変換されてしまうので
$.ajax({
type: "POST",
url: "https://www.googleapis.com/urlshortener/v1/url",
// ...
});↓こんなエラーに悩まされるオチ。dataTypeをjsonpにしても無駄な足掻きっす。
{
error:{
errors:[{
domain:"global",
reason:"required",
message:"Required",
locationType:"parameter",
location:"shortUrl"
}],
code:400,
message:"Required"
}
}