【发布时间】:2017-09-29 15:24:38
【问题描述】:
我希望我的指数像亚马逊一样根据价格下降和价格上升而变化。
现在,我向站点发送了一个 ajax 请求,其中 select 的新值请求数据。该站点从数据库中获取数据并对其进行排序。之后,我的 javascript 使用排序好的图书响应重绘索引页面中的卡片。
但是当我控制台记录结果时,我得到了整个 html 页面。
下面这行代码给了我错误:
var books = JSON.parse(result);
JSON 中位置 0 处的意外标记
我怎样才能只获得@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
图书索引.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
【问题讨论】:
-
错误意味着响应包含 XML 或 HTML,而不是您告诉它期望的 JSON
-
是的,它给了我整个 html ......但这真的很奇怪,因为它不应该只从我的@books 中获取对象吗因为我说从 BooksController.rb 获取索引?
标签: javascript jquery ruby-on-rails ajax