我得到'json is null'为错误
我的php文件:
<?php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$url='https://www.googleapis.com/urlshortener/v1/';
$key='ApiKey';
$result= $url.($query).$key;
$ch = curl_init($result);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
}
?>
我的HTML:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// when the user clicks the button
$("button").click(function(){
$.getJSON("shortner.php?query="+$('#query').attr("value"),function(json){
$('#results').append('<p>Id : ' + json.id+ '</p>');
$('#results').append('<p>Longurl: ' + json.longurl+ '</p>');
});
});
});
</script>
</head>
<body>
<input type="text" value="Enter a place" id="query" /><button>Get Coordinates</button>
<div id="results"></div>
编辑:
<?php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$url='https://www.googleapis.com/urlshortener/v1/';
$key='Api';
$key2='?key=';
$result= $url.$query.$key2.$key;
$requestData= json_encode($result);
echo var_dump($query);
$ch = curl_init($requestData);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
}
?>
答案 0 :(得分:2)
为我工作:
<?php
$ch = curl_init("https://www.googleapis.com/urlshortener/v1/url?key=MYAPIKEY&shortUrl=http://goo.gl/fbsS");
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$res = curl_exec($ch);
if (!$res)
var_dump(curl_error($ch)); else
echo "Yay! I've got JSON result!";
curl_close($ch);
?>
仍然有bit.ly服务具有类似但功能更强大的功能。以下是如何使用它的示例(完美地工作):
<?php
if (array_key_exists("url", $_GET) && $_GET["url"] != "")
{
$u_name = "YOUR BIT.LY USERNAME";
$u_apikey = "YOUR BIT.LY API KEY";
$f = fopen("http://api.bit.ly/v3/shorten?login=" . $u_name . "&apiKey=" . $u_apikey . "&longUrl=" . rawurlencode($_GET["url"]) . "&format=json", "r");
header("Content-Type: application/json");
ob_start();
echo stream_get_contents($f);
fclose($f);
ob_end_flush();
exit;
}
?>
<html>
<head>
<title>jCarousel Examples</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("[name=send]").click(function() {
$.getJSON("index.php?url=" + $('[name=url]').val(), function(f) {
$('[name=res]').append('<p>Shorten: ' + f.data.url + '</p><br/ >');
});
});
});
</script>
</head>
<body>
<input type="text" name="url" size="30" />
<input type="button" name="send" value="shorten!" />
<br /><div name="res"></div>
</body>
</html>
UPD:要获得bit.ly API密钥,请在bit.ly网站上注册并转到您的帐户(在顶部) - &gt;设置。