Ruby:2.4.1
Rails:5.2.3
jQuery:3.4.1
通过Ajax从页面发送请求,该页面的格式为json
,但是Rails服务器认为此请求的格式为text/html
。
因此,它生成ActionView::MissingTemplate
。
ActionView::MissingTemplate (Missing template likes/json, application/json with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :arb, :slim, :coffee, :jbuilder]}
routes.rb
Rails.application.routes.draw do
resources :likes, only: %i(create destroy)
控制器
class LikesController < ApplicationController
def create
item = Item.find(like_params[:item_id])
like = Like.new(user: current_user, item: item)
if like.save
count = Like.where(item: item).count
render :json, { count: count, like_id: like.id }
else
render :json, {}
end
end
view(slim)
.like-btn
a href='#'
.count = @like_count
javascript:
$('.like-btn a').click( e => {
e.preventDefault()
$.ajax({
url: '#{likes_path(item_id: @item.id)}',
dataType: 'json',
method: 'POST',
success: (data) => {
$('.like-btn .count').text(data.count)
}
})
})
respond_to
render :plain, some_json, content_type: 'application/json
$.post
contentType
,type
,data
请求对象
# inside LikesController#create
(byebug) request.headers.to_h["CONTENT_TYPE"]
"application/x-www-form-urlencoded"
(byebug) request.format.to_s
"text/html"
我尝试了#{likes_path(item_id: @item.id)}.json
和'likes?item_id=#{@item.id}
,但它们不起作用并产生了相同的错误。
这里是请求对象。网址中没有json
,即使javascript中的网址具有text/html
,该格式也被识别为json
。
# inside LikesController#create
byebug) request.url
"http://localhost:3001/likes?item_id=4"
(byebug) request.format
#<Mime::Type:0x007feea72326a0 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html", @hash=-2254575977737173308>
尝试将.json
附加到URL
url: "#{likes_path(item_id: @item.id, format: :json)}"
它应该起作用!