gpt4 book ai didi

javascript - 从 api 响应中获取特定值

转载 作者:行者123 更新时间:2023-11-30 10:59:09 24 4
gpt4 key购买 nike

我向 PHP 文件发送 Ajax 请求,PHP 文件向 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 }]}

如何从该结果中获取 lnglat

最佳答案

由于代理将来自第三方 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);

关于javascript - 从 api 响应中获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com