简体   繁体   English

Rails Ajax意外令牌<JSON中的位置0

[英]Rails Ajax Unexpected token < in JSON at position 0

I want my Index to change according to Price descending and Price ascending just like Amazon. 我希望我的指数像亚马逊一样根据价格下降和价格上升而变化。

Right now, I send an ajax request to the site, with the new value of the select requesting the data. 现在,我将一个ajax请求发送到该站点,其中带有选择该数据的select新值。 The site gets the data from database and sorts it. 该站点从数据库获取数据并对其进行排序。 After that, my javascript redraws the cards in my index page with the sorted book response. 之后,我的javascript用排序后的书本响应在索引页面中重新绘制卡片。

But when I console.log the result I get the whole html page. 但是,当我console.log结果时,我得到了整个html页面。
This line of code below gives me the error: 下面的代码行给了我错误:

var books = JSON.parse(result);

Unexpected token < in JSON at position 0 BookController.rb JSON中的意外令牌<在位置0 BookController.rb中

How can I only get the @books? 我怎么只能得到@books?
Below is my code: 下面是我的代码:

BookController.rb 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
  respond_to do |format|
    format.html
    format.json { render json: @books }
  end
end

Book Index.html.erb 图书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>
.
.
.
<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>

<script>
  $('#priceSelect').change(function(){
    $.ajax({
      url: "books",
      type: "GET",
      data: {sort: $('#priceSelect :selected').val()},
      success:function(ret){
        console.log(ret);
        var books = JSON.parse(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>

And lastly my routes.rb 最后是我的routes.rb

resources :books do
  resources :users
end

Change this 改变这个

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

to: 至:

render json: {data: @books}

I think you're missing the accept header in your Ajax request so you're actually getting the HTML page back again. 我认为您在Ajax请求中缺少accept标头,因此实际上是在重新获取HTML页面。

Try: 尝试:

$.ajax({
  dataType: 'json',
  ...
});

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

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