使用JSON使用Javascript缩短URL

时间:2013-02-10 11:33:35

标签: javascript jquery short short-url

我正在尝试缩短链接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
}

请求缩短网址

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)
    }
});

1 个答案:

答案 0 :(得分:0)

使用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;
    }
  }