繁体   English   中英

如何使用 js.erb 响应 fetch(post)?

[英]How to respond to a fetch(post) with js.erb?

我正在尝试发出一个帖子请求,该请求将获取所有事件(Jams)并通过 ajax 动态更新页面。 所以我的 controller 收到 JSON 格式的参数,我想用 js 来回应,就像你在链接或按钮上使用 remote: true 一样。

我正在使用导轨 6.0.2.2

这是在 my.js 文件中 =>

const getJams = () => {
  const mapCenter = map.getCenter();
  const mapBounds = map.getBounds();
  const token = document.getElementsByName("csrf-token")[0].content
  fetch(window.location.origin + "/search", {
    method: "POST",
    headers: {
      'Accept': "text/javascript",
      'Content-Type': "application/javascript",
      'X-CSRF-Token': token
    },
    body: JSON.stringify({
      map_center: mapCenter,
      max_lat: mapBounds._ne.lat,
      min_lat: mapBounds._sw.lat,
      max_lng: mapBounds._ne.lng,
      min_lng: mapBounds._sw.lng
    }),
    credentials: "same-origin"
  })
}

搜索发送数据的controller中的方法是这样的=>

def index
    @jams = policy_scope(Jam)

    respond_to do |f|
      f.json do |f|
        render json: {
          jams: render_to_string(
            partial: 'jams/jams',
            formats: :html,
            layout: false,
            locals: { jams: @jams }
          )
        }
      end
    end
  end

像这样执行,在我的 byebug 中存在参数,所以这似乎是正确的。 如果我继续我的服务器会显示这个

Completed 406 Not Acceptable in 1ms (ActiveRecord: 0.0ms | Allocations: 889)



ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/searchs_controller.rb:7:in `index'

我想在那个 search.js.erb 文件中工作到 append 我视图中的元素。 虽然,我的 search.js.erb 只包含console.log("a"); 但是那个js似乎没有被执行。 控制台中不显示任何内容。

如果有人可以帮助我,我将不胜感激。

这是果酱的内部/_jam.html.erb 部分 =>

<% jams.each do |jam| %>
<div class="jam-card">
  <%= image_tag jam.photo %>
  <%= jam.status %>
  <%= jam.user.first_name %>
  <%= jam.music_style.music_style %>
  <%= display_date(jam.start_date_time, jam.duration) %>
  <%= jam.participants.count %>/<%= jam.max_participants %>
</div>
<% end %>

暗示。 您不需要js.erb模板。

  • 他们把流程弄得一团糟。 当您使用js.erb模板时,您现在正在 Ruby 和 JavaScript 以及每行的服务器端和客户端之间进行上下文切换。 这种心理体操不会促进高质量的代码。
  • js.erb模板不由资产管道/webpacker 提供,因此不会由 CDN 缩小或提供。
  • 你知道你精心制作的那个安静的服务器端应用程序吗? 吻别它,因为它现在负责客户端转换,并且充满了摆动 woggle 路线和 spagetti 代码 javascript 视图。

Either respond to the request with an array of JSON objects and let the client side handle templating or pass a HTML string back in the JSON response and let your real ajax handler actually do its job:

def index
  @jams = policy_scope(Jam)
  respond_to do |f|
    f.json do 
      render json: { 
        jams: render_to_string(
          partial: 'jams/jams', 
          formats: :html, 
          layout: false, 
          locals: { jams: @jams}
        )
     }
    end
  end
end

.then(function(response) {
  document.getElementById("some_element").innerHTML = response;
})

还有一些方法,人们使用request.xhr发送回 HTML ajax 请求或使用自定义内容类型的 HTML 请求的块。 所有这些js.erb更好。

暂无
暂无

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

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