用Ajax响应替换div的内部HTML
我试图在一段时间后改变div的内部HTML。 我得到了正确的响应,我想用Ajax。 但无法替换后选择的内部HTML和Ajax响应。 我的代码有什么问题..
HTML
51 seconds ago
58 seconds ago
. . . . . 10 minute ago
j查询
setInterval(function() { $( ".time" ).each(function( index ) { var sendTime= $(this).attr("data-time"); dataString = "sendtime="+sendTime+"&q=convertTime"; $.ajax({ type: "POST", url: "data_handler.php", data: dataString, cache: true, success: function(response) { alert(response); $(this).html(response); //alert(response); } }); }); }, 5000);
this
是回调中的窗口。 使用给每个callback
的值:
$( ".time" ).each(function(index , elem) { var sendTime= $(this).attr("data-time"); dataString = "sendtime="+sendTime+"&q=convertTime"; $.ajax({ type: "POST", url: "data_handler.php", data: dataString, cache: true, success: function(response) { alert(response); $(elem).html(response); } }); });
你不需要定义一个新变量来保护this
因为jQuery已经为你做了。
当您使用带回调的异步函数时,回调中的this
函数不会来自相同的上下文。 您需要将其保存在回调中使用的变量中。
试试这样:
setInterval(function() { $( ".time" ).each(function( index ) { var sendTime= $(this).attr("data-time"); dataString = "sendtime="+sendTime+"&q=convertTime"; var self = this; $.ajax({ type: "POST", url: "data_handler.php", data: dataString, cache: true, success: function(response) { alert(response); $(self).html(response); //alert(response); } }); }); }, 5000);
我认为$(this)是脱离背景的。 尝试:
setInterval(function() { $( ".time" ).each(function( index ) { var $this = $(this); var sendTime= $(this).attr("data-time"); dataString = "sendtime="+sendTime+"&q=convertTime"; $.ajax({ type: "POST", url: "data_handler.php", data: dataString, cache: true, success: function(response) { alert(response); $this.html(response); //alert(response); } }); }); }, 5000);
setInterval(function() { $( ".time" ).each(function( index ) { var sendTime= $(this).attr("data-time"); var _thisvariable = $(this); dataString = "sendtime="+sendTime+"&q=convertTime"; $.ajax({ type: "POST", url: "data_handler.php", data: dataString, cache: true, success: function(response) { alert(response); _thisvariable.html(response); //alert(response); } }); }); }, 5000);