jQuery 線上生成 t.cn 新浪短網址
6,646 0
最近在學習 Ajax 技術,所以就經常會寫一些小 Demo 出來,比如上次寫的「jQuery 線上取得 QQ 名稱和頭像」,今天我帶來的也是一個 Ajax 專案,主要功能是線上生成 t.cn 的新浪短網址,我看過網路上很多的壓縮網址,都是需要輸入網址然後點擊按鈕才會執行的,我這個不需要喔。
HTML 程式碼
HTML HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>在线生成 t.cn 短网址</title>
<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div> 长链接 <input type="text" name="" id="longurl" value="" /></div><br>
<div> 短链接 <input type="text" name="" id="shorturl" value="" /></div><br>
<script>
$("#longurl").blur(function() {
var url = $("#longurl").val();
$.ajax({
type: "get",
url: "https://v1.ikxin.com/api/tcnurl.php?from=txt&url=" + url,
success: function(data) {
$("#shorturl").val(data);
},
error: function() {
$("#shorturl").val("获取失败");
}
});
})
</script>
</body>
</html>
PHP 程式碼
PHP PHP
<?php
$apiurl = 'http://api.t.sina.com.cn/short_url/shorten.json'; // 新浪短网址 json 接口
$source = '3271710248'; // 新浪 source 验证码
$geturl = $_GET ['url'];
$format = $_GET ['format'];
switch ($format){
case "text":
if(substr($geturl, 0, 4) != 'http'){
echo "您的输入有误!";
}else{
$suo_url = sprintf($apiurl.'?source='.$source.'&url_long='.$geturl);
$dwzcode = file_get_contents($suo_url);
$dwz = str_replace(array('[',']'), '', $dwzcode);
$dwzurl = json_decode($dwz,true);
echo $dwzurl['url_short'];
}
break;
case "json":
if(substr($geturl, 0, 4) != 'http'){
echo "您的输入有误!";
}else{
$suo_url = sprintf($apiurl.'?source='.$source.'&url_long='.$geturl);
$dwzcode = file_get_contents($suo_url);
$oldarr = array('[',']','url_short','url_long',',"type":0');
$newarr = array('','','shorturl','longurl','');
$dwz = str_replace($oldarr, $newarr, $dwzcode);
echo $dwz;
}
break;
case "jsonp":
if(substr($geturl, 0, 4) != 'http'){
echo "您的输入有误!";
}else{
$suo_url = sprintf($apiurl.'?source='.$source.'&url_long='.$geturl);
$dwzcode = file_get_contents($suo_url);
$oldarr = array('[',']','url_short','url_long',',"type":0','{','}');
$newarr = array('','','shorturl','longurl','','callbackUrl({','})');
$dwz = str_replace($oldarr, $newarr, $dwzcode);
echo $dwz;
}
break;
default:
echo "您的输入有误!";
}
評論
(0)暫無評論,來說兩句吧