2
Je suis en train de court un lien sur API et obtenir le résultat avec JSONRaccourcir URL avec JavaScript en utilisant JSON
Quelques informations sur l'API
Exemple de réponse
{"error":0,"short":"http:\/\/doma.in\/sf0x6"}
échantillon utilisation en PHP
[email protected]_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
}
Demande de Raccourcir une URL longue
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 devrait vous en empêcher. Vous devez utiliser un point de terminaison JSONP à la place – Alexander
Merci pour votre réponse, mais je suis un débutant au codage. Pourriez-vous me dire où je devrais utiliser JSONP? – user2036282
Le raccourcisseur d'URL doit prendre en charge JSONP. Sinon, vous devez utiliser PHP pour cela. Quoi qu'il en soit, il est préférable d'utiliser PHP sur le serveur pour cela car votre clé d'application n'est pas divulguée ouvertement – Alexander