简体   繁体   English

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

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

I am trying to make a post request that'll grab all events(Jams) and update dynamically the page via ajax.我正在尝试发出一个帖子请求,该请求将获取所有事件(Jams)并通过 ajax 动态更新页面。 So my controller recieves params in JSON format and I'd like to respond with js just like how you would do with remote: true on a link or button.所以我的 controller 收到 JSON 格式的参数,我想用 js 来回应,就像你在链接或按钮上使用 remote: true 一样。

I am using rails 6.0.2.2我正在使用导轨 6.0.2.2

This is in my.js file =>这是在 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"
  })
}

The method in the search controller where the data is sent is like this =>搜索发送数据的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

Executed like this, inside my byebug the params are present, so that seems correct.像这样执行,在我的 byebug 中存在参数,所以这似乎是正确的。 If I continue my server shows me this如果我继续我的服务器会显示这个

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



ActionController::UnknownFormat (ActionController::UnknownFormat):

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

I'd like to work inside that search.js.erb file to append the elements inside my view.我想在那个 search.js.erb 文件中工作到 append 我视图中的元素。 Though, my search.js.erb contains simply console.log("a");虽然,我的 search.js.erb 只包含console.log("a"); but that js seems not to be executed.但是那个js似乎没有被执行。 Nothing appears in the console.控制台中不显示任何内容。

If anyone could help me I'd be grateful.如果有人可以帮助我,我将不胜感激。

Here is the inside of the jams/_jam.html.erb partial =>这是果酱的内部/_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 %>

Hint.暗示。 You don't need js.erb templates.您不需要js.erb模板。

  • They make an absolute mess of the flow.他们把流程弄得一团糟。 When you reach for a js.erb template you're now context switching between Ruby and JavaScript and server side and client side on every line.当您使用js.erb模板时,您现在正在 Ruby 和 JavaScript 以及每行的服务器端和客户端之间进行上下文切换。 This mental gymnasics does not promote good quality code.这种心理体操不会促进高质量的代码。
  • js.erb templates are not served by the assets pipe/webpacker and are thus not minified or served by a CDN. js.erb模板不由资产管道/webpacker 提供,因此不会由 CDN 缩小或提供。
  • You know that nice restful server side app you carefully crafted?你知道你精心制作的那个安静的服务器端应用程序吗? Kiss it goodbye because its now responsible for client side transformations and full of wiggle the woggle routes and spagetti code javascript views.吻别它,因为它现在负责客户端转换,并且充满了摆动 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: 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;
})

There are also approaches where people have used request.xhr to send back chunks of HTML in response to a HTML ajax request or used custom content types.还有一些方法,人们使用request.xhr发送回 HTML ajax 请求或使用自定义内容类型的 HTML 请求的块。 All of them are better then js.erb .所有这些js.erb更好。

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

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