[英]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 縮小或提供。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.