【发布时间】:2016-05-03 00:12:34
【问题描述】:
我想要实现的目标:当用户输入完邮政编码后,自动完成将显示所有可能的有效地址。
我是如何尝试这样做的:当用户输入他们的邮政编码(6 或 7 个字符)时,在他们的输入延迟一秒钟后,自动完成将调用 AJAX 函数,该函数将返回 JSON,它将被翻译为自动完成以显示客户端。
问题:我没有在浏览器上显示任何内容,而且我每天只能调用 api 20 次,以下是返回的 JSON 示例。
返回的我感兴趣的 JSON 是字符串数组地址,而不是经度和纬度。我看到的与此类似的其他示例和问题在其 JSON 中具有键和值结构,以便于映射。
问题:如何让 AJAX 调用返回的地址显示在自动完成下拉菜单中?我可以将它们吐出到一个 div 中,但自动完成似乎没有承认任何事情。我已经包含了必要的资源:@987654321@ 和 https://code.jquery.com/ui/1.10.4/jquery-ui.js
来自 AJAX 的 JSON: - 修剪结果,因为有很多:
{
"Latitude":51.991799,
"Longitude":-1.078074,
"Addresses":[
"1 Stable Close, , , , Finmere, Buckingham, Buckinghamshire",
"10 Stable Close, , , , Finmere, Buckingham, Buckinghamshire",
"12 Stable Close, , , , Finmere, Buckingham, Buckinghamshire",
"14 Stable Close, , , , Finmere, Buckingham, Buckinghamshire",
"16 Stable Close, , , , Finmere, Buckingham, Buckinghamshire"
]
}
JavaScript:
var typingTimer; //timer identifier
var typingInterval = 2000; // 2 second delay
var pc = $('#pcode');
var divArray = $('#out4');
//on keyup, start the countdown
pc.keyup(function() {
clearTimeout(typingTimer);
if (pc.val) {
typingTimer = setTimeout(function() {
postcodeDelay();
}, typingInterval);
}
});
function postcodeDelay() {
apiurl = 'https://api.getAddress.io/v2/uk/' + String(pc.val()) + '?api-key=key';
// ajax call to the api too get JSON object of addresses that match the postcode entered
$.ajax({
type: "GET",
url: apiurl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: possiblePostcodes
});
}
function possiblePostcodes(data) {
pc.autocomplete({
source: data.Addresses
});
}
HTML:
<div class="ui-widget">
<label for="pcode">Enter a Postcode:</label>
<input id="pcode" type="text" />
</div>
【问题讨论】:
标签: javascript jquery json ajax autocomplete