Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Rails flash notice via ajax

Long story short, I have a button. On clicking it, I want an ajax request to be triggered which gets flash[:notice] and displays it in a div in$

Here is my shortened view:

 <input type="button" id="search" value="display"/>

 <div id="notice">

 </div>

My ajax request in the view:

$("#search").submit(function(){
                            $.ajax({
                                type: "POST",
                                url: //url to my show action
                                success: function(data){
                                      /*$("#notice").html("<%= flash[:notice] %>");
                                        $("#content").html(data);*/
                                }
                            });
                            return false;
                    });

My controller:

def HomeController <  ActionController::Base
  def index

  end

  def show
    respond_to do |format|
    format.js {  flash[:notice] = "" + count.to_s + " results found for " + params[:query][:search_key] + "" }
    end
    #render :partial => 'search'
  end
end

My show.js.erb

#app/views/dashboard_home/show.js.erb
$("#notice").html("<%=j flash[:notice] %>");

$("#content").html("<%=j render partial: "search" %>");

The problem is when I click on button, the notice is displayed fine. But the same notice persists on the next clicks too. The search partial contains the table Please help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is an example that I got working, thanks to Rich Peck's answer. I needed to use flash.now to make sure the flash notice didn't persist.

AJAX trigger in the view:

<%= link_to "Email report", users_path, remote: true %>

Controller:

# app/controllers/users_controller
class UsersController < ApplicationController

  def index
    # do some things here

    respond_to do |format|
      format.js { flash.now[:notice] = "Here is my flash notice" }
    end
  end
end

Rendered view:

# app/views/users/index.js.erb
$("#flash").html('<%= j render partial: "shared/notice_banner" %>');

where the flash notice is displayed in the layout:

# app/views/layouts/application.html.erb
<div id="flash">
  <% if notice.present? %>
    <%= render partial: "shared/notice_banner" %>
  <% end %>
</div>


# app/views/shared/_notice_banner.html.erb
<div data-alert class="alert-box">
  <%= notice %>
  <a href="#" class="close">&times;</a>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...