【问题标题】:How to include string variable of html code in javascript response?如何在 javascript 响应中包含 html 代码的字符串变量?
【发布时间】:2013-09-02 22:45:17
【问题描述】:

在我的控制器的显示操作中,我们准备了一堆信息来构建一个 html 表,该表通过 jquery 替换表所在的 div 返回到浏览器。

这一部分被解释为纯文本,并未添加到表格中。所以我在编码方面做错了,我收集,但到目前为止我尝试过的并没有改善结果。

控制器的显示动作,部分:

@shared_individuals = Individual.where(:address_id => params[:id]).order("birthdate ASC")
@typecodes = Contactmethods.select("Distinct typecode_desc, typecode_id")
@contact_methods = getem( @typecodes, @shared_individuals)

getem() 是控制器中的函数,它为表格做了很多复杂的排列和 html 编码,但为了简化尝试找出问题所在,目前只是这样做:

def getem( @typecodes, @shared_individuals )
   foo = "<tr><td>Testing</td></tr>"
   return foo
end

控制器的显示动作被称为AJAX事务,因此视图代码为show.js.erb:

$('#selected_family')
    .replaceWith('<div id="selected_family">' +
        '<%=j render partial: "addresses/selected_address", object: @selected_address %>' +
        '<table border="1px" rules=all frame=box cellspacing="5" cellpadding="5">' +
            '<tr>' +
                '<th></th><%=j render partial: "review/first_names", collection: @shared_individuals %>' +
            '</tr>' +
            '<tr>' +
                '<td><strong>Birthday</strong></td><%=j render partial: "review/birth_dates", collection: @birth_dates %>' +
            '</tr>' +
            '<tr>' +
                '<td><strong>Phone</strong></td><%=j render partial: "review/phone_numbers", collection: @phone_numbers %>' +
            '</tr>' +
            '<tr>' +
                '<td><strong>Email</strong></td><%=j render partial: "review/emails", collection: @emails %>' +
            '</tr>' +
            '<%=j @contact_methods %>' +
        '</table>' +
        '</div>')
    .show("blind");

所以流程是 show 方法使用一串 HTML 代码填充 @contact_methods,我要求 erb 在 javascript 响应中插入 HTML。

浏览器中实际发生的是我们看到的表格上方

< tr>< td>Testing< /td>< /tr>

(html标签并没有真正分开,但我不知道如何让stackoverflow标记语言不理会它们) 然后表格正确表示,但其中不包含该行。

我试过了:

   '<%=h @contact_methods %>' +  #wasn't that from Rails 1.0? 
   '<%=  @contact_methods %>' +  #nothing shows up

我什至尝试过:

   '#{@contact_methods}' + #but of course that's silly in this context

为什么不呢:

   @contact_methods + #that blows up the javascript processing

【问题讨论】:

    标签: jquery html ajax ruby-on-rails-4


    【解决方案1】:

    我以不同的方式解决了这个问题,它更符合 MVC 约定:控制器创建视图所需的所有数据的集合,但不将其包装在 HTML 中。部分执行所有 HTML 包装。然后注意 和 之间的区别也总是很聪明!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 2021-07-24
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多