javascript - 从 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}]}
如何从该结果中获得lng
and lat
?
解决方案
由于代理将来自第三方 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);
推荐阅读
- amazon-web-services - 部署 efs 堆栈时出现以下错误
- perl - Perl Template Toolkit - 如何将模板输出结果返回到变量中?
- r - 在将其降低到R中的阈值以下之前获取系列中的最后一个数字
- javascript - 如何使用 setTimeout 在 if 条件内返回 JSX 元素
- azure - VSCode:请求连接/GetChildrenForTreeItemRequest 失败,ECONNREFUSED 127.0.0.1:3306
- css - CSS border-bottom-left-radius 不适用于 :before 部分的 mozilla
- node.js - 如何通过剧作家导出 blob 文档来捕获下载事件
- c++ - 有没有办法重载类上所有可能的函数?
- python - 为什么在启动单个工作人员时 sanic 会产生多个线程?
- vba - 寻找更好的方法来设置表单控件的属性