Я пытаюсь найти ответ, но я могу найти только с помощью jquery, но в моем случае я не могу его использовать.
Как я могу обновить мой частичный, не перезагружая мою страницу?
У меня есть эта страница new.html.erb, которая содержит кнопку каждый раз, когда я нажимаю на эту кнопку, она вызывает мою функцию вjavascript.
Кроме того, он также отображает мою таблицу, в которой отображаются сохраненные данные
// new.html.erb
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<h1 id="countdown">10</h1>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="button" class="btn btn-outline-primary" onclick="saveMyGame()">Save play</button>
</div>
<div class="col-md-4"></div>
</div>
<br>
<div id="plays"><%= render 'table' %></div>
// _ table.html.erb
<table class="table">
<thead>
<tr>
<th scope="col">Tick</td>
<th scope="col">Index of image in the array</td>
</tr>
</thead>
<tbody>
<% Play.all.each do |play| %>
<tr>
<td><%= play.current_time %></td>
<td><%= play.image_url %></td>
</tr>
<% end %>
</tbody>
</table>
// savegame.js.erb
function saveMyGame() {
var countdown = document.getElementById("countdown").innerHTML
var xhr = new XMLHttpRequest();
xhr.open('POST', '/plays/save_my_play');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== countdown) {
alert('Something went wrong. Countdown is now ' + countdownt);
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI('countdown=' + countdown));
}
В моем контроллере я могу получить данные и сохранить свою модель
// plays_controller.rb
class PlaysController < ApplicationController
protect_from_forgery with: :null_session
def index
@plays = Play.all
end
def create
@play = Play.new(post_params)
if @play.save
render :new
end
end
def new
@play = Play.new
@plays = Play.all
end
def save_my_play
# create an array with all the images selected
@game = Game.last
array_images = Array.new()
@game.images.each do |image|
array_images.push(url_for(image))
end
# get the countdown from ajax request
countdown = params[:countdown]
# save the model Play
play = Play.new
play.current_time = countdown
play.image_url = array_images.index(array_images.sample)
play.save
@plays = Play.all
end
private
def post_params
params.require(:play).permit(:current_time, :image_url)
end
end