正文
最近在学习Ajax技术,所以就经常会写一些小Demo出来,比如上次写的《jQuery在线获取QQ名称和头像》,今天我带来的也是一个Ajax项目,主要功能是在线生成 t.cn 的新浪短网址,我看过网上很多的压缩网址,都是需要输入网址然后点击按钮才会执行的,我这个不需要喔!
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
$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 "您的输入有误!";
}