仍在尝试修复我的ajax以使用控制器。 现在我收到此错误消息:
response SyntaxError: Unexpected token j , xhr[object Object] , STATUS parsererror
config.routes
resources :books do
member do
get '/last_chapter/', to: 'chapters#last_chapter', as: 'last_chapter', defaults: { format: 'json' }
end
resources :chapters
end
章节控制器
def last_chapter
@last_chapter = Chapter.order(created_at: :desc).limit(1)
respond_to do |format|
format.json
end
end
last_chapter.json
json.extract! @last_chapter, :id, :title, :characters, :created_at, :updated_at
script.js
$.ajax({
type: "GET",
url: '/books/103/last_chapter.json',
contentType: "application/json",
success: function(data) {
console.log('JAAAA ENDELIG FUNKER DET');
$("body").html(data);
},
error: function(xhr, status, response) {
console.log('response ' + response + ' , xhr' + xhr + ' , ' + 'STATUS ' + status)}
});
感觉我已经尝试了一切。如果您需要更多信息,请告诉我们! :)
答案 0 :(得分:1)
我认为你的问题在于路线。这就是我要做的事情:
resources :books do
get :last_chapter, on: :member
end
<强> books_controller.rb 强>
def last_chapter
@last_chapter = Book.find(params[:id]).chapters.last
respond_to do |format|
format.json do
render json: { does_it_work: :yes }
end
end
end
我假设以下模型:
class Book < ActiveRecord::Base
has_many :chapters
end