使用 Ajax 调用呈现 flash 消息

Render flash message with Ajax call

我正在调用 ajax 删除一个对象。一切正常,但现在我需要它显示一条 flash 消息,让用户知道该对象已被删除。我似乎找不到一种简单的方法来做到这一点。这是我的代码。

控制器

    def destroy
    DestroySnitch.perform(snitch: @snitch)

    respond_to do |format|
      format.html do
        redirect_to snitches_path, notice: "Snitch was successfully deleted."
      end
      format.json do
        render json: [], status: :no_content
      end
    end
  end

AJAX

    $(document).on('click','.destroy-snitch', function(event) {
  var snitchID = $(this).attr('data-snitch-id');
  $.ajax({
    dataType: 'json',
    type: 'DELETE',
    url: '/snitches/' + snitchID,
    success: function(){
      $('#tr-for-snitch-' + snitchID).fadeOut();
    }
  });

  $('.modal').modal('hide');

  $('.jquery-modal.blocker').hide();

  event.preventDefault();
});

如果您还需要查看其他内容,请告诉我?感谢您的帮助。

如果通过 AJAX 调用它,可能请求为 JSON。如果请求过来JSON,那么它不会重定向它,但是会发送消息。

您只需要处理 AJAX 回调、消息和重定向!

def destroy
   DestroySnitch.perform(snitch: @snitch)

  respond_to do |format|
    format.html {redirect_to snitches_path, notice: "Snitch was successfully deleted."}
    format.json {render json: message: "DELETED COOL", status: :no_content} 
  end
end