简体   繁体   English

如何在Rails的Ajax调用中的js响应中包含html标签

[英]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. create action中,不需要键入@result.html_safe ,因为它实际上在这里什么也不做。 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 : 然后,在create.js.erb中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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