[英]jQuery AJAX loads json contents at page load, would rather load it when typing in search box
我不確定為什么會這樣,但是當我的頁面加載時,會立即為搜索結果發出XHR請求。 它對用戶是不可見的,但它正在加載相當大的json數據塊。
這是我的代碼:
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
我怎樣才能這樣做只有當用戶在輸入#搜索框中鍵入時才會請求json數據?
看起來您想要加載列表自動完成結果,然后僅在用戶開始輸入時初始化自動完成插件。 為此,將鍵盤功能綁定到搜索框,如果尚未加載結果,則加載結果並初始化插件。
$(document).ready(function(){
var searchInput = $("input#search");
function loadData(onSuccess){
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: onSuccess,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function initializeAutocomplete(data){
searchInput.addClass('loaded').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
searchInput.val(ui.item.value).closest('form').submit();
}
});
}
searchInput.keyup(function(){
if($(this).is(".loaded")) return;
loadData(initializeAutocomplete);
});
});
將ajax調用包裝到button.click()事件中,或者如果您希望在用戶鍵入時調用它,請將其放在textbox.keypress()事件中。
您需要將keyup事件偵聽器綁定到輸入框。 如果你在沒有事件監聽器的情況下在html頁面中插入了這段代碼,代碼將在你的頁面加載后立即執行。
這應該可行: http : //jsfiddle.net/XNbrX/
我沒有測試過。
我不知道我是否理解你,但我認為您希望在每次按鍵(真正按鍵)上運行此代碼,以便在每次更改搜索框值時加載結果。 如果我是對的,請將您的代碼放入'onkeyup'事件觸發的函數中。
$('input#search-box').keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.