更新Rails HTLM表,使用ajax,vanilla javascript

时间:2018-05-31 06:50:09

标签: javascript ruby-on-rails ajax

我试图找到答案,但我只能找到使用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

2 个答案:

答案 0 :(得分:1)

更改以下文件:

// 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() {
      console.log(this.responseText);
        if (xhr.status === 200) {
          document.getElementById("plays").innerHTML = this.responseText;
        }
        else if (xhr.status !== 200) {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    auth_token = document.head.querySelector("[name=csrf-token]").content;
    xhr.send(encodeURI('countdown=' + countdown + '&authenticity_token=' + auth_token));

}

创建以下视图:

// app/views/plays/save_my_play.js.erb

<%= render 'table' %>

当按下按钮时,javascript函数将对plays/save_my_play进行AJAX调用。

在处理控制器方法之后,服务器将呈现视图app/views/plays/save_my_play.js.erb,这将使表格部分显示。

javascript函数saveMyGame将使用从服务器收到的响应更新您的#plays

答案 1 :(得分:0)

结帐https://learnetto.com/blog/how-to-make-ajax-calls-in-rails-5-1-with-or-without-jquery

基本上,Rails 5.1现在可以很好地支持ujs库中的ajax