正确返回JSON格式到页面

Properly returning JSON format to page

本文关键字:格式 JSON 返回      更新时间:2023-09-26

我正在尝试捕获纬度和经度,然后将其传递给Google Maps以返回一些数据,然后从响应中精确获取邮政编码并使用它。

当我直接调用它到浏览器时,我在页面上得到的响应最终是这样的:

{"zip":"90029"}

但是当我试图在Chrome的开发人员工具中查看它时,它指出"此请求没有响应数据"。因此,似乎我的JSON没有被正确编码,或者我没有以JSON格式类型头正确返回到页面。

我试过各种各样的东西,似乎没有什么工作正常,以获得它返回JSON数据。

这是我现在的代码:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$now = @date("Ymd-His");
$myFile = "loc" . $now . ".txt";
$fh = fopen("locations/" . $myFile, 'w') or die("can't open file");
$lat = $_REQUEST['lat'];
$long = $_REQUEST['long'];
$type = $_REQUEST['type'];
$phone = $_REQUEST['phone'];
$loc = $_REQUEST['typed_location'];
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";


$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData, true);
$temp_data = $address['results'][0]['formatted_address'];
$temp = explode(", ", $temp_data);
$temp_2 = explode(" ", $temp[2]);
$zip = $temp_2[1];
fwrite($fh, $zip);
fclose($fh);

$array = array("zip" => $zip);
$t = json_encode($array);
echo $t;

对于其他想要解决这个问题的人-当使用跨域时,请确保通过设置以下内容作为标题来允许访问控制:

header("access-control-allow-origin: *");