从Rails Ajax请求获得响应后,Javascript重做html

时间:2017-09-27 14:26:07

标签: javascript ruby-on-rails ajax

我希望我的索引根据价格下降和价格上涨来改变,就像亚马逊一样。

现在,我向网站发送一个ajax请求,其中select的新值请求数据。该站点从数据库中获取数据并对其进行排序。

我的javascript如何使用已排序的图书回复重绘我的索引页面中的卡片?

BookController.rb

def index
  if params.dig("book", "title").nil? && params.dig("users", "university").nil?
    @books = Book.where({title: params.dig("book", "title")})
    .joins(:user).where(users: {university: params.dig("users", "university")})
  elsif !params.dig("book", "title").nil? && params.dig("users", "university").nil?
    @books = Book.where({title: params.dig("book", "title")})
  elsif params.dig("book", "title").nil? && !params.dig("users", "university").nil?
    @books = Book.joins(:user).where(users: {university: params.dig("users", "university")})
  else
    @books = Book.all
  end
  case params[:sort]
    when "Price Descending"
      @books.order(price_cents: "DESC")
    when "Price Ascending"
      @books.order(price_cents: "ASC")
    else
      @books.sort_by(&:created_at)
  end
end

预订Index.html.erb

<select id="priceSelect">
  <option value="Best Results" selected="selected">Best Results</option>
  <option value="Price Descending">Price Descending</option>
  <option value="Price Ascending">Price Ascending</option>
</select>

.
.
.

<% @books.each do |book| %>
  <div class="col-xs-12 selectable-card">
    <%= link_to book_path(book.id) do %>
      ...   
    <% end %>
  </div>
<% end %>

<script>
  $('#priceSelect').change(function(){
    $.ajax({
      url: "books",
      type: "GET",
      data: {sort: $('#priceSelect :selected').val()},
      success:function(result){
        console.log(result);
      },
    })
  });
</script>

最后我的routes.rb

resources :books do
  resources :users
end

1 个答案:

答案 0 :(得分:1)

这个答案可能有语法错误或其他问题,正如我在这里写的那样,没有经过测试。它只是如何做到这一点的指南。采取这些想法并纠正任何可能的问题。

在你的控制器中你可以返回一个json对象:

respond_to do |format|
  format.html
  format.json { render json: @books }
end

在你的html中,添加一个div来标记要替换的区域:

<div class ="books-info">
  <% @books.each do |book| %>
    <div class="col-xs-12 selectable-card">
      <%= link_to book_path(book.id) do %>
        ...   
      <% end %>
    </div>
  <% end %>
</div>

在你的javascript中你应该处理json响应并构建html来替换原始列表:

<script>
  $('#priceSelect').change(function(){
    $.ajax({
      url: "books",
      type: "GET",
      data: {sort: $('#priceSelect :selected').val()},
      success:function(ret){
        // new code;
        var books = JSON.parse(ret); // Not sure if necessary or you can use 'ret'            
        var length = books.length;
        var html = "";
        for (var i = 0; i < length; i++) {
          html += "<div class='col-xs-12 selectable-card'>";
          html += "<a href='" + books[i].id + "'>" + books[i].name + "</a>";
          html += "</div>";
        }
        $('.books-info').innerHTML = html
      },
    })
  });
</script>