繁体   English   中英

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

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

我希望我的指数像亚马逊一样根据价格下降和价格上升而变化。

现在,我将一个ajax请求发送到该站点,其中带有选择该数据的select新值。 该站点从数据库获取数据并对其进行排序。 之后,我的javascript用排序后的书本响应在索引页面中重新绘制卡片。

但是,当我console.log结果时,我得到了整个html页面。
下面的代码行给了我错误:

var books = JSON.parse(result);

JSON中的意外令牌<在位置0 BookController.rb中

我怎么只能得到@books?
下面是我的代码:

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

图书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>

最后是我的routes.rb

resources :books do
  resources :users
end

改变这个

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

至:

render json: {data: @books}

我认为您在Ajax请求中缺少accept标头,因此实际上是在重新获取HTML页面。

尝试:

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

暂无
暂无

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

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