簡體   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