问题
Two JQuery Ajax calls. First brings back user messages from MySQL, the number of likes for that message and a button for the user to like the message. This request is working.
Second Ajax request to fire from the user pressing the like button created from the first Ajax request. However, nothing appears to happen on pressing the button (no errors). Tried to view the results as an alert or in the console but nothing happened.
Ajax request 1:
dataType: 'json',
success: function(response) {
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' :'';
$( '.content' ).append( '<div class="post"><div class="post-text"> ' +item.MessageText+ ' </div><div class="post-action"><input type="button" value="Like" id="like_'+item.ID+'_'+item.UserID+'" class="like" '+mycss+' /><span id="likes_'+item.ID+'_'+item.UserID+'">'+item.cntLikes+'</span></div></div>');
});
});
}
Example of the html produced:
<div class="post"><div class="post-text"> This is message example text. </div><div class="post-action"><input type="button" value="Like" id="like_1_f6khb11ldm2hek6bvs3qd2oef6" class="like"><span id="likes_1_f6khb11ldm2hek6bvs3qd2oef6">12</span></div></div>
Ajax request 2:
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
EDIT: On click second Ajax request code as requested:
$(".like").click(function(){
回答1:
have you tried to echo the target? or just simple alert? if that not working it means the target is not sighted, this is specially when the elements are appended. so you need to have a static target
$("#static-target").on("click",".real-target",function(){
//do here
});
来源:https://stackoverflow.com/questions/59707409/jquery-ajax-total-likes-not-updating-for-post-when-pressing-like-button