【发布时间】:2013-02-10 11:33:34
【问题描述】:
我正在尝试通过 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)
}
});
【问题讨论】:
-
CORS 应该阻止你这样做。您需要改用 JSONP 端点
-
感谢您的回复,但我是编码初学者。你能告诉我应该在哪里使用 JSONP 吗?
-
URL 缩短器需要支持 JSONP。否则,您需要坚持使用 PHP。无论哪种方式,最好在服务器端使用 PHP,因为这样您的应用程序密钥就不会公开
-
你知道你在这里缺少一个引号 ["short":doma.in/mnQRi"] 就在冒号后面吗?
-
好吧,你的意思是样本响应。
标签: javascript jquery short short-url