Last active
March 10, 2016 02:41
-
-
Save kenzo0107/88af2f3e961324fac815 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# [bitly Generic Access Token] は https://bitly.com/a/oauth_apps より 生成してください。 | |
# | |
# 以下のようなinputボックスを想定しています。 | |
# <input type="text" name="hogehoge" value="" class="bitly"> | |
var generateUrl = (function () { | |
// 短縮化するURLの文字列数. 以下の場合30文字未満の場合短縮化しない。 | |
var SHORTEN_URL_LENGTH = 30; | |
// フォームから値を取得 | |
function getUrl() { | |
$(".bitly").on("keyup", function () { | |
var btnOnkeyup = $(this); | |
var url_val = btnOnkeyup.val(); | |
if (url_val.length < SHORTEN_URL_LENGTH) { | |
return; | |
} | |
// 結果を表示 | |
convertBitly(url_val, 'bitly.com').done(function (d) { | |
if (d.data.url) { | |
btnOnkeyup.val(d.data.url); | |
} | |
}); | |
}); | |
} | |
// Bitly APIにリクエスト | |
function convertBitly(url, domain) { | |
var encUrl = encodeURIComponent(url); | |
console.log('encUrl = ' + encUrl); | |
var bitly = "https://api-ssl.bitly.com/v3/shorten?access_token=[bitly Generic Access Token]&longUrl=" + encUrl + "&domain=" + domain; | |
var d = new $.Deferred(); | |
$.ajax({ | |
type: "get", | |
url: bitly, | |
dataType: "jsonp", | |
processData: false, | |
contentType: false, | |
success: d.resolve, | |
error: d.reject | |
}); | |
return d.promise(); | |
} | |
return { | |
init: function () { | |
getUrl(); | |
} | |
}; | |
} ()); | |
$(document).ready(function () { | |
generateUrl.init(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment