// Cart Code for Updating Database Quantity
$('.input-text').on('keydown ' , function(){
var tr_parent = $(this).closest("tr");
setTimeout(function () {
$(tr_parent).css('opacity', '0.3');
}, 4000);
var input_value = $(this).val();
var input_value_length = input_value.length;
var product_id_update = $("#product_id").attr('data');
if(input_value_length > 0 ) {
// Setting up time to execute jquery
setTimeout(function () {
$.ajax({
url: "includes/ajax_code.php",
data:{input_value:input_value, product_id_update : product_id_update},
type: "POST",
success:function(data) {
$(tr_parent).css('opacity', '0.9');
}
});
}, 5000);
}
});
这里的代码是将输入元素的不透明度设置为 0.3,只是为了给用户一些数据正在传输的指示,我的问题是当我在 AJAX 的成功区域设置第二个函数 setTimeout 时它不会执行。
因此输入始终保持不透明度或 0.3,而不是在 AJAX 完成后变为 0.9。
最佳答案
我认为您应该在调用 ajax 之前立即将第一个不透明度设置为 0.3,以指示某些内容开始加载。并在成功/错误/完成回调中将其设置回 0.9。
$('.input-text').on('keydown change', function() {
var table_row = $(this).closest("tr");
// $(table_row).css('opacity', '0.3');
var input_value = $(this).val();
var input_value_length = input_value.length;
var product_id_update = $("#product_id").attr('data');
if (input_value_length > 0) {
$(table_row).css('opacity', '0.3');//<-- move here
$.ajax({
...
...
and in success callback, set it back to 0.9...either instantly or with a slight delay, doesnt matter.
注意:看起来您正在尝试在每次按键时提交数据,这可能有点低效。我认为你应该“限制”这个 ajax 函数。 当用户编辑输入时设置一个计时器,比如 1 秒。 当时间用完时,使用 ajax 发送输入值。 当用户键入另一个字母时,计时器会重置,因此,仅当用户完成键入至少一秒钟后才会触发 ajax。它的简单优化。
*编辑 - 创建了 jsfiddle 演示来展示它应该如何完成 * 演示 - http://jsfiddle.net/rainerpl/49mjkagv/
<input type="text" class="input-text">
<img src="http://www.minefornine.com/pages/tpl/front/images/ajax_loader_big.gif" style="width: 24px; float: left;display: none;" id="loader" >
$(document).ready(function() {
var input = $('.input-text');
var timer;
var loader = $("#loader");
var loadStuff = function() {
//input changed - set opacity to 0.4 to indicate loading
input.css("opacity", 0.4);
loader.show();
setTimeout(function() {
//loading finished
input.css("opacity", 1);
loader.hide();
}, 2000);//<--simulates ajax call
};
input.on('keydown ' , function() {
if ( timer ) {clearTimeout(timer);}
timer = setTimeout(loadStuff, 1000);;
});
});
关于javascript - 设置 UP 第二个 setTimeout 函数不会执行 JQUERY 和 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880261/