我还不太擅长 JSON,所以如果这是一个主要的新手错误,请原谅。我正在向本地文件发送查询,该文件对外部站点的 API 执行 cURL 并获取 JSON 对象。因为我必须为 API 的 x 查询付费,所以我只是复制并粘贴了一个,并用它来代替 cURL。我有以下脚本:
$.ajax({
type: 'GET',
url: 'ajax.php?v='+value, //with this being an input value, which is totally irrelevant because I'm not actually doing the cURL query anyway
dataType: 'json',
success:function(json){
var o_response = json;
json = $.parseJSON(json);
alert(o_response.toSource());
alert(json.toSource());
},
error: function (xhr, ajaxOptions, thrownError) {
alert('There appears to be a problem with the information you submitted. Please try again or contact us.');
}
});
ajax.php 中的 PHP 如下所示:
<?
if (isset($_GET['v']) && $_GET['v'] != '') {
$response = '[{"query":"14-22-25-02-W5","response":{"status":"ok","err":[],"lat":51.152259,"lng":-114.202199,"country":"Canada","province":"AB","city":"Calgary","street":"49 Royal Vista Drive NW","street_prox":78,"address":"49 Royal Vista Drive NW, Calgary, AB","lsd":"14-22-25-2 W5","lsd_border":[[51.150459,-114.199327],[51.150447,-114.205067],[51.154059,-114.205071],[51.154072,-114.199332],[51.150459,-114.199327]],"uwi":"","nts":"","nts_border":[],"utm":"11S 695661E 15670479N","utm_v":"Zone 11, 695661 meters easting, 15670479 meters northing (Southern Hemisphere)"}}]';
echo json_encode($response);
}
?>
$response 与 API 给我的完全一样。
我想做的是从中获取“lat”和“lng”值。我的 JavaScript 文件中的第一个示例“alert(o_response.toSource());” bit 使它变成一个字符串,这很好,但我想要一个对象。第二个例子“alert(json.toSource());” 使其成为一个对象,但删除所有键周围的引号。例如,它这样做:
[{query:"14-22-25-02-W5", response:{status:"ok", err:[], lat:51.152259, lng:-114.202199, country:"Canada", province:"AB", city:"Calgary", street:"49 Royal Vista Drive NW", street_prox:78, address:"49 Royal Vista Drive NW, Calgary, AB", lsd:"14-22-25-2 W5", lsd_border:[[51.150459, -114.199327], [51.150447, -114.205067], [51.154059, -114.205071], [51.154072, -114.199332], [51.150459, -114.199327]], uwi:"", nts:"", nts_border:[], utm:"11S 695661E 15670479N", utm_v:"Zone 11, 695661 meters easting, 15670479 meters northing (Southern Hemisphere)"}}]
注意“query”、“response”、“status”、“lat”、“lng”等如何不再有引号。我想这是它应该工作的方式。那么,如果我尝试通过执行以下操作来获得“响应”:
alert(json.response);
alert(json['response']);
alert(json[1]);
我得到的只是 3 个未定义的警报。
我显然错过了一些东西。是不是格式不对?我是否在解析或编码不应该的东西?
任何帮助将不胜感激。
谢谢你。