我正在使用谷歌地图 API。我在 .keyup() 上使用 $.getJSON 对地址进行地理编码。这显示了每种类型的 key 在 map 上的位置。问题是如果你打字太快,它就会卡住。这是因为 $.getJSON 在太短的时间内访问 Google DB 的次数太多。我正在考虑放置延迟();或者代码上的东西。但是,这似乎不起作用。这是 jQuery:
$('#create_loc_input').keyup(function() {
var loc = $('#create_loc_input').val();
$.getJSON('http://localhost/app/search/search.json.php?loc='+loc, function(data) {
lat = data.results[0].geometry.location.lat;
lng = data.results[0].geometry.location.lng;
$.post('app/create_page/func/create_page_messages.func.php', {
lat:lat,
lng:lng,
},
function(data) {
$('#create_latlng').html(data);
codeAddress();
});
});
});
代码显然还有很多内容。但是,在这里,我如何将查询限制为每 3 秒左右一次。有点像 sudo keyup()。将 $.getJSON 限制为每 3 秒最多一个请求会很好。这可能吗?我在不同的地方尝试了delay()。但是,到目前为止,这还没有完成这项工作。
最佳答案
在 keyup 上使用 setTimeout()
安排 $.getJSON()
调用三秒的时间,然后在后续的 keyup 上取消任何未完成的超时并设置另一个超时。这样,JSON 请求仅在最后一次击键后三秒发生(并且在上一次请求后至少三秒发生)。
var timeoutID = null;
$('#create_loc_input').keyup(function() {
if (timeoutID != null)
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
timeoutID = null;
// all of your other code here
}, 3000);
});
关于php - 当发生太多 $.getJSON 请求时,keyup 函数会卡住页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8131679/