简体   繁体   中英

How to include html tags in a js response in ajax call in Rails

I have a controller method for login my app like this:

def create
  user = User.find_by(mail: params[:session][:mail].downcase)
  if user && user.authenticate(params[:session][:password])
    if user.confirmed? 
        # Stuff when login is OK
        .......         
    else
        logout
        text = I18n.t("error.login.confirmation", :link => ActionController::Base.helpers.link_to(I18n.t("button"), confirm_user_path(user), :class => 'btn btn-info'))
        @result = ActionController::Base.helpers.sanitize(text, :tags => ['br','a']).html_safe
        respond_to do |format|
            format.html { render 'new' }
            format.js { @result.html_safe }

        end
    end
  # more stuff
  .......
  end  
end

If the user has not confirmed the email, I want to show him a message with a link to re-send the confirmation mail:

 Please confirm your signup. <br /> <br /> <a class="btn btn-info" href="/users/48/confirm_user">Re-send confirmation mail.</a>

UPDATE: This is how render the view

$("p.bg-danger").html("<%= @result %>")

In create action, it is not needed to type @result.html_safe , because it's actually does nothing here. Instead, you would like probably to tell your controller not to render layout.

def create
  # ...
  respond_to do |format|
    format.html { render 'new' }
    format.js { render layout: false }

  end
end

Then, within create.js.erb :

$("p.bg-danger").html('<%=j @result %>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM