Skip to content

Instantly share code, notes, and snippets.

@laomo
Created November 27, 2013 07:43
Show Gist options
  • Save laomo/7672018 to your computer and use it in GitHub Desktop.
Save laomo/7672018 to your computer and use it in GitHub Desktop.
新浪短链接生成js版
var url_shorten = "http://api.weibo.com/2/short_url/shorten.json";
function ltrim(str){ //删除左边的空格
return str.replace(/(^\s*)/g,"");
}
function rtrim(str){ //删除右边的空格
return str.replace(/(\s*$)/g,"");
}
function trim(str){ //删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function checkUrl(url){
data=url.match(/(http|https):\/\/.+/);
if(!data||!url) {
return false;
}
return true;
}
function getShortenUrl() {
var url_long = $("#url_long").val();
if(trim(url_long)==""){
alert("请先输入网址!");
return false;
}
if(url_long.indexOf("http://")==-1&&url_long.indexOf("https://")==-1){
url_long = "http://"+url_long;
}
if(!checkUrl(url_long)){
alert("请输入正确网址!");
}
var url = url_shorten + "?source=1681459862&url_long="
+ encodeURIComponent(url_long) + "&callback=?";
return url;
};
/*
* {"urls":[{"result":true,"url_short":"http://t.cn/zjrQFOs","url_long":"http://lmbj.net/","type":0}]}
*/
function getShorten() {
var url = getShortenUrl();
$.getJSON(url, function(data) {
/*
alert(data.data.urls[0].url_short);
var urls = data.data.urls;
for ( var i = 0; i < urls.length; i++) {
alert(urls[i].result);
alert(urls[i].url_short);
alert(urls[i].url_long);
alert(urls[i].type);
}
*/
$("#result").html(data.data.urls[0].url_short);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment