您还可以在服务器上使用 php 和 curl 生成一个短 url,这样您就不必在网页中公开您的 API 密钥:
<?php
//the long url posted by your webpage
$url = strip_tags($_POST["url"]);
$api_user = "your_bitly_user_name";
$api_key = "your_bitly_api_key";
//send it to the bitly shorten webservice
$ch = curl_init ("http://api.bitly.com/v3/shorten?login=$api_user&apiKey=$api_key&longUrl=$url&format=json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//the response is a JSON object, send it to your webpage
echo curl_exec($ch);
?>
然后在您的网页中,代码应类似于:
//the long url that you want to shorten
var longUrl = escape(window.location.href)
$.ajax({
url : "php/getShortUrl.php",//this is the php script above
dataType : "json",
type : "POST",
data : {
url : longUrl
},
success : function(data) {
if(data.status_txt === "OK"){
shortUrl = data.data.url;
}
},
error : function(xhr, error, message) {
//no success, fallback to the long url
shortUrl = longUrl
}
});
有关详细信息,请参阅bitly API