使用JSON通过Javascript缩短URL

Shorten URL with Javascript using JSON

本文关键字:缩短 URL Javascript 通过 JSON 使用      更新时间:2023-09-26

我正在尝试通过API缩短链接,并使用JSON 获得结果

关于API 的一些信息

样本响应

{"error":0,"short":"http:'/'/doma.in'/sf0x6"}

PHP中的示例用法

$content=@file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array
if(!$url["error"]){  // If there is no error
  echo $url["short"]; //Outputs the short url
}
else{ 
  echo $url["msg"]; //Outputs the error message
}

请求缩短长URL

GET http://doma.in/api/?url=http://www.google.com&api=APIKEY

*json_short.php*

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
$url = curPageURL();
$json_short = @file_get_contents("http://doma.in/api/?url=$url&api=APIKEY");
echo $json_short;

*json_short.js*

$.getJSON('json_short.php', function(data) {
    if(!data.error){ // If there is no error
        alert(data.short) //Outputs the short url
    }
    else{
        alert(data.msg)
    }
});

使用JavaScript简化流程:

var foo = window.location.href;
var bar = foo.replace(/[a-z0-9.]+'//g, shortener);
function shortener(match, pos, fullstring)
  {
  if (shortener.count === foo.match(/[a-z0-9.]+'//g).length)
    {
    shortener.count = 0;
    }
  else
    {
    shortener.count = shortener.count + 1 || 0;
    }
  if (shortener.count === 1)
    {
    return "";
    }
   else
    {
    return match;
    }
  }