【问题标题】:Is it possible to intertwine Javascript and erb?是否可以将 Javascript 和 erb 交织在一起?
【发布时间】:2020-04-02 20:33:38
【问题描述】:

我想这样做,但显然这是错误的。有什么方法可以让 ajax 返回 'cnut' 进入 erb?

processResults: function (data, params) { 
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;
        return {
          results: $.map(data, function(cnut) {
              <% asdf = BandRole.where(band_id: cnut.id).first %>
              <% member = Fan.find(asdf.fan_id) %>
              var band_member = <% member.name %>
              return { 
                text: cnut.name + ", " + cnut.city + " (" + band_member + ")",
                id: cnut.id,
              };  
          }),
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },

【问题讨论】:

    标签: javascript ruby-on-rails erb


    【解决方案1】:

    如果你告诉 Rails 渲染 JS 而不是 JSON,你可以。

    在您的控制器设置中,您的 respond_to 块如下所示:

    respond_to do |format|
      format.html
      format.js { render :your_view }
    end
    

    然后创建一个名为your_view.js.erb 的视图。您可以像使用普通 HTML 视图一样使用它,只是您可以像在示例中那样将 JavaScript 和 Ruby 放入此文件中。但是,这是在响应中发送回浏览器的 JS,而不是处理响应的 JS。我希望这有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2019-09-27
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多