From 7fdaae2fcf2a0a64d295aa5da43c3ebb16a5ebbe Mon Sep 17 00:00:00 2001 From: Aaron Parecki Date: Sun, 30 Sep 2012 10:22:08 -0700 Subject: [PATCH] Supports jsonp callbacks --- index.php | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/index.php b/index.php index e676466..1a2288d 100644 --- a/index.php +++ b/index.php @@ -1,7 +1,7 @@ TRUE)); $latitude = get('latitude') ?: $match[1]; @@ -9,29 +9,37 @@ $timezone = timezoneFromLocation($latitude, $longitude); - header('Content-type: application/json'); - if($timezone) { $tz = new DateTimeZone($timezone); $now = new DateTime(date('c')); $now->setTimeZone($tz); - echo json_encode(array( + respond(array( 'timezone' => $timezone, 'offset' => $now->format('P'), 'seconds' => (int)$now->format('Z') )); } else { - echo json_encode(array( + respond(array( 'error' => 'no_data' )); } } else { header('HTTP/1.1 404 Not Found'); - header('Content-type: application/json'); - echo json_encode(array( + respond(array( 'error' => 'not_found' )); } +function respond($data) { + header('Content-type: application/json'); + if(preg_match('/callback=([^\&]+)/', $_SERVER['REQUEST_URI'], $match) || get('callback')) { + $cb = get('callback') ?: $match[1]; + echo $cb . '('; + echo json_encode($data); + echo ')'; + } else { + echo json_encode($data); + } +} \ No newline at end of file