使用JSON使用Javascript缩短URL

使用JSON使用Javascript缩短URL,javascript,jquery,short,short-url,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 a

我试图通过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;
    }
  }

CORS应该阻止你这么做。您需要改用JSONP端点,谢谢您的回复,但我是一名编码初学者。你能告诉我应该在哪里使用JSONP吗?URL缩短器需要支持JSONP。否则,您需要坚持使用PHP。无论哪种方式,在服务器端使用PHP都会更好,因为这样您的应用程序密钥就不会被公开披露。您知道您在这里遗漏了一个引号[“short”:冒号后面右键?好的,您的意思是在示例响应中。