如何以 ajax 方式更改 dom 元素,但不使用 javascript 方式替换 dom 内容

How to change dom element in ajax way but not replace the dom content using javascript way

本文关键字:dom javascript 内容 替换 方式 ajax 方式更 元素      更新时间:2023-09-26

默认情况下,页面将显示up vote button

用户单击up button后,页面将再次重新加载,然后显示down vote button

现在我想在不加载页面的情况下以 Ajax 方式执行此操作,

但是如何在不重新加载页面的情况下更改按钮?

  - if not comment.has_evaluation?(:votes, current_user)
    = link_to vote_comment_path(comment, type: "up"), method: :post do
      %button.btn.btn-xs.btn-success
        Like this
  - else
    = link_to vote_comment_path(comment, type: "down"), method: :post do
      %button.btn.btn-xs.btn-danger
        Unlike this

我假设您使用背景图像来控制up votedown vote按钮。试试这个:

var $btn = $('#btn-id');
$.ajax({
    url: '/rate',
    data: {key: value},
    type: 'post'
}).done(function(res) {
    if (res.success) {
       if (res.myRate.up) {
           $btn.removeClass('down-vote-bg');
           $btn.addClass('up-vote-bg');
       } else {
           $btn.removeClass('up-vote-bg');
           $btn.addClass('down-vote-bg');
       }
    }
}).fail(function() {
    alert('Action failed');
});

查看 jQuery Ajax API 了解更多信息。