tvi*_*ira 43 ruby ajax respond-to ruby-on-rails-4
在我的rails应用程序中,我有一个ajax请求到服务器,以存储一些数据.这曾经没有任何问题,但现在我收到一个错误:
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/reservations_controller.rb:45:in `create'
Run Code Online (Sandbox Code Playgroud)
以下是控制器和我的javascript文件,其中我声明数据类型是JSON
class ReservationController < ApplicationController
respond_to :html, :json
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
render 'new'
end
end # respond_to
end # create
end # ReservationController
Run Code Online (Sandbox Code Playgroud)
function.js
$.ajax({
url: url_link,
dataType: 'json',
type: 'POST',
data: dataToSend
})
Run Code Online (Sandbox Code Playgroud)
完整的错误日志是:
Completed 406 Not Acceptable in 45ms
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/bookings_controller.rb:45:in `create'
Rendered /Users/tiagovieira/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)
Rendered /Users/tiagovieira/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.8ms)
Rendered /Users/tiagovieira/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /Users/tiagovieira/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (9.6ms)
Run Code Online (Sandbox Code Playgroud)
Kir*_*rat 47
更新create
操作如下:
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @reservation.errors } ## You might want to specify a json format as well
end
end
end
Run Code Online (Sandbox Code Playgroud)
您正在使用respond_to
的方法,但ANOT指定格式,其中new
呈现页面.因此,错误ActionController::UnknownFormat
.
BPH*_*BPH 25
您还可以修改config/routes.rb文件,如:
get 'ajax/:action', to: 'ajax#:action', :defaults => { :format => 'json' }
Run Code Online (Sandbox Code Playgroud)
这将默认格式为json.它在Rails 4中对我很好.
或者,如果您想进一步使用命名空间,可以减少重复项:
namespace :api, defaults: {format: 'json'} do
#your controller routes here ...
end
Run Code Online (Sandbox Code Playgroud)
以上所有内容/api
默认情况下将格式化为json.
还有另一种情况会重现此问题(如我的情况)。当客户端请求的 URL 中不包含正确的扩展名时,控制器无法识别所需的结果格式。
例如:控制器设置为respond_to :json
(作为单个选项,没有 HTML 响应)- 而客户端调用设置/reservations
为而不是/reservations.json
。
最重要的是,将客户端调用更改为/reservations.json
.
归档时间: |
|
查看次数: |
122398 次 |
最近记录: |