问题
I'm sending POST data from text boxes to a PHP page for processing. Rather than the user clicking a save button, AJAX is used on text box events.
I'm torn between using onChange or onKeyUp.
OnKeyUp requires more processing on server, because for every key press my script has to access the database and make the change. Server performance could be an issue.
OnChange is preferred, as it only sends the changes when the user has finished on the box. However, there is a problem that if the use does not deselect the text box, the event 'onChange' doesn't happen, so changes aren't saved.
Which would be best? Or is there a way to enforce 'onChange' without the user deselecting the box?
回答1:
You can even use the KeyUp press ajax call, how?? Just add the delayKeyUp function on keyUp event, and delayKeyUp function has setTimeout method, this would really help you out as per as server processing concern,
Note: This works fine for one method at a time.
Ex. Code:
Update:
$("selector").live('keyup', function(e) { //if jquery v1.7 or more then you can use .on event instead of .live
delayKeyUp(function(){ ---Your Server Call Stuff -----}, 350); //delay of 350ms.
return false;
});
var delayKeyUp = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
回答2:
In what scenario would the user not blur the textbox, resulting in the AJAX not happening?
One possible solution is to set a timeout to keyDown and keyUp so that after a certain period of no typing, the AJAX will fire, something along these lines. This probably has a bug in that it may not update the textbox if you start typing in another one before that textbox's $.ajax
has run, but you should be able to get the idea
var key_is_down = false,
key_timeout;
$(el).on('keyDown', function () {
key_is_down = true;
}).on('keyUp', function () {
key_is_down = false;
key_timeout = setTimeout(function(){ runAjax($(this)); }, 2500);
});
function runAjax ($el) {
if (key_is_down) {
key_timeout = setTimeout(function(){ runAjax($el); }, 2500);
} else {
// $.ajax...
}
}
回答3:
window.page_loaded = new Date();
$('text_field').bind('keyup', function(){
var timeout_seconds = 10;
var last_check = $(this).data('last_checked');
last_check = last_check ? last_check : window.page_loaded;
var curr_time = new Date();
curr_time = new Date(curr_time.getTime() - (timeout_seconds * 1000));
if(last_check < curr_time){
//now do the checking
}
});
来源:https://stackoverflow.com/questions/12858069/on-key-up-vs-on-change-with-ajax-queries-which-is-better