首页 > 解决方案 > 从 api 响应中获取特定值

问题描述

我向 PHP 文件发送 Ajax 请求,该文件向 API 发送 CURL 请求,然后返回结果。

PHP代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.example.com?country=usa');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$response = array('result' => $result);
echo json_encode($response);

Javascript/jQuery 代码:

$.ajax({
    url: "file.php",
    type: "POST",
    dataType : "json",
    success: function(data){
        console.log(typeof(data.result));
        console.log(data.result);
    }
});

结果的类型是string,结果如下所示:

{"results":[{"code2":"093","code1":"NY","lng":-73.9395687,"name1":"New York","lat":42.8142432}]}

如何从该结果中获得lngand lat

标签: javascriptphpjqueryajax

解决方案


由于代理将来自第三方 API 的响应作为 JSON 编码字符串返回,因此您需要手动反序列化它。您可以使用JSON.parse(). 然后您可以results通过索引访问数组中的对象。尝试这个:

var data = {
  result: '{"results":[{"code2":"093","code1":"NY","lng":-73.9395687,"name1":"New York","lat":42.8142432}]}'
}

// inside your AJAX callback:
var obj = JSON.parse(data.result);
var lat = obj.results[0].lat;
var lng = obj.results[0].lng;

console.log(lat);
console.log(lng);


推荐阅读