从 jQuery GET JSON 响应字符串中获取单个值
Posted
技术标签:
【中文标题】从 jQuery GET JSON 响应字符串中获取单个值【英文标题】:Get an individual value from a jQuery GET JSON response string 【发布时间】:2016-02-04 16:50:06 【问题描述】:我查看了一些类似的主题并尝试了这些建议,但我无法让它发挥作用。
在此页面http://www.thefuelcardpeople.co.uk/test-pump-locator/ 我有一个按钮,可以从地理位置数据中获取经纬度坐标,然后连接到https://api.postcodes.io/postcodes API 以进行反向邮政编码查找。
我已经让它返回完整的数据字符串,它显示了这一点,但我不知道如何只返回邮政编码值。我想使用 API 从地理位置数据返回的邮政编码值预填充表单字段输入。
有人可以帮忙吗?
这是我的代码:
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<p id="demo2"></p>
<pre id="geocode-postcode-result" class="code-box" style="display: block;"></pre>
<script>
var x = document.getElementById("demo");
var y = document.getElementById("demo2");
function getLocation()
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(showPosition);
else
x.innerhtml = "Geolocation is not supported by this browser.";
function showPosition(position)
var lon = position.coords.longitude;
var lon2 = lon.toFixed(14);
var lat = position.coords.latitude;
var lat2 = lat.toFixed(14);
x.innerHTML = "Latitude: " + lat2 + "<br>Longitude: " + lon2;
var $result = jQuery("#geocode-postcode-result");
var displayJsonResult = function ($context, data)
$context.html(JSON.stringify(data, null, 4)).slideDown();
jQuery.get("https://api.postcodes.io/postcodes?lon=" + lon2 + "&lat=" + lat2 + "&limit=1")
.done(function (data)
displayJsonResult($result, data);
)
.fail(function (error)
displayJsonResult($result, error.responseJSON);
);
</script>
感谢您的回复 - 收到的回复是:
"status": 200,
"result": [
"postcode": "BB11 2DB",
"quality": 1,
"eastings": 384278,
"northings": 432561,
"country": "England",
"nhs_ha": "North West",
"longitude": -2.2401189327649,
"latitude": 53.7891288271951,
"parliamentary_constituency": "Burnley",
"european_electoral_region": "North West",
"primary_care_trust": "East Lancashire Teaching",
"region": "North West",
"lsoa": "Burnley 003D",
"msoa": "Burnley 003",
"incode": "2DB",
"outcode": "BB11",
"distance": 30.904269682,
"admin_district": "Burnley",
"parish": "Burnley, unparished area",
"admin_county": "Lancashire",
"admin_ward": "Daneshouse with Stoneyholme",
"ccg": "NHS East Lancashire",
"nuts": "East Lancashire",
"codes":
"admin_district": "E07000117",
"admin_county": "E10000017",
"admin_ward": "E05005155",
"parish": "E43000093",
"ccg": "E38000050",
"nuts": "UKD46"
]
【问题讨论】:
你能发布一个返回字符串的例子吗?在那之后应该很简单 感谢您的回复 - 作为上面的编辑添加的回复。 【参考方案1】:假设您给出的字符串是调用中返回的data
的全部,您只需这样做:
data.result[0].postcode
这将为您提供一个仅代表邮政编码的字符串,您可以随意使用它。
【讨论】:
非常感谢 - 我在代码中遗漏了(或放错了)[0]。以上是关于从 jQuery GET JSON 响应字符串中获取单个值的主要内容,如果未能解决你的问题,请参考以下文章
Python - 从 JSON 响应中提取数据(使用 TomTom api)