我已经查看了几个相似的主题,并尝试了这些建议,但无法使其工作。从jQuery GET JSON响应字符串获取单个值
本页内容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"
}
}
]
}
你能发表一个返回字符串的例子吗?应该是相当微不足道的 – Pabs123
谢谢你的答复 - 答复作为上面的编辑添加。 – dcrosby