Ruby-on-rails ActionController::UnknownFormat 和 format.js 用于 ajax 实现(Rail 4)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25074739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:50:11  来源:igfitidea点击:

ActionController::UnknownFormat with format.js for ajax implementation (Rail 4)

ruby-on-railsajaxruby-on-rails-4

提问by Ahamadi

i try to use Ajax in my application with Rails 4. To send my js to the client i use :

我尝试在 Rails 4 的应用程序中使用 Ajax。要将我的 js 发送到客户端,我使用:

   respond_to do |format|
        format.js 
   end

in my controller. But it's generated error "ActionController::UnknownFormat" i my controller. Someone can help me please ?

在我的控制器中。但是它在我的控制器中生成了错误“ActionController::UnknownFormat”。有人可以帮我吗?

main_controller.rb:

main_controller.rb:

class Oweb::MainController < ApplicationController
    def index
        .....
    end
    def setmagasinstatus
      begin                     
       @mag = Magasin.find(params[:id]) 
       if @mag.etatmagasin.lib == 'Ouvert'
            @mag.etatmagasin = Etatmagasin.where(lib: 'Fermé').first
       else
            @mag.etatmagasin = Etatmagasin.where(lib: 'Ouvert').first
       end 
      rescue ActiveRecord::RecordNotFound
       logger.error("Attempt to access invalid Magasin #{params[:id]}")
       redirect_to_index("Invalid Magasin")
      else
       @mag.save
       @mags = Magasin.where(user_id: current_user.id) 

       respond_to do |format|
            format.js 
       end

     end
    end
end

setmagasinstatus.js.erb :

setmagasinstatus.js.erb :

page.replace_html("bloc_magasin", :partial => "listmagasins", :object => @mags)

layouts/application.html.slim:

布局/application.html.slim:

doctype html
html
    head
        meta charset="utf-8"
        meta http-equiv="X-UA-Compatible" content="IE=edge"
        meta name="viewport" content="width=device-width, initial-scale=1.0"
        meta name="description" content=""
        meta name="author" content=""

        title = yield(:title)

        = stylesheet_link_tag "application"
        = csrf_meta_tags

    body
     .........
                = yield

        = javascript_include_tag "application"
        = yield :scripts

gemfile:

宝石文件:

source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'

group :development do
  gem 'mysql2'
end
group :production do
  gem 'pg'
end

gem 'sass-rails', '~> 4.0.3'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.0.0'

gem 'therubyracer',  platforms: :ruby


gem 'jquery-rails'

gem 'turbolinks'

gem 'jbuilder', '~> 2.0'

gem 'sdoc', '~> 0.4.0',          group: :doc

gem 'spring',        group: :development

gem 'devise', '~> 3.2.4'

gem 'slim-rails', '~> 2.1.4'

gem 'bootstrap-sass', '~> 3.1.1.1'

gem 'compass-rails', '~> 1.1.7'

gem 'simple_form', '~> 3.0.2'
gem 'activeadmin', github: 'gregbell/active_admin'

gem 'polyamorous', github: 'activerecord-hackery/polyamorous'

gem 'ransack', github: 'activerecord-hackery/ransack'

gem 'formtastic', github: 'justinfrench/formtastic'

 gem 'debugger', group: [:development, :test, :production]

gem 'geocoder'
gem 'gmaps4rails', '~> 2.1.2'

logs:

日志:

Started GET "/oweb/main/setmagasinstatus?id=3" for 192.168.56.1 at 2014-08-01 06:22:06 +0000
Processing by Oweb::MainController#setmagasinstatus as HTML
  Parameters: {"id"=>"3"}
Completed 406 Not Acceptable in 103ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/oweb/main_controller.rb:24:in `setmagasinstatus'


  Rendered /home/vagrant/.rvm/gems/ruby-2.1.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (2.1ms)
  Rendered /home/vagrant/.rvm/gems/ruby-2.1.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.2ms)
  Rendered /home/vagrant/.rvm/gems/ruby-2.1.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
  Rendered /home/vagrant/.rvm/gems/ruby-2.1.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (27.1ms)

采纳答案by RAJ

Catch:

抓住:

Your console log says:

您的控制台日志说:

Processing by Oweb::MainController#setmagasinstatus as HTML

由 Oweb::MainController#setmagasinstatus 处理为 HTML

In your controller action, you don't have supported HTML response. That's why you are facing error of UnknownFormat.

在您的控制器操作中,您没有受支持的 HTML 响应。这就是为什么您面临UnknownFormat.

Solution:

解决方案:

Add format: "js"in your ajax call. For example:

添加format: "js"您的 ajax 调用。例如:

$.ajax url: "/oweb/main/setmagasinstatus", data: 'id=' + id, format: 'js'

回答by alishir

If you can use link_tohelper function to call action of your controller, in your case Oweb::MainController#setmagasinstatusadding :remote => trueto link_tohelper will solve the issue.

如果您可以使用link_tohelper 函数来调用控制器的操作,那么在您的情况下Oweb::MainController#setmagasinstatus添加:remote => truelink_tohelper 将解决问题。

For example if you have a link to your action and want to get response in ajax the following code will create the link to that action:

例如,如果您有指向操作的链接并希望在 ajax 中获得响应,则以下代码将创建指向该操作的链接:

<%= link_to your_link_name, setmagasinstatus_path(:params), :remote => true %>

<%= link_to your_link_name, setmagasinstatus_path(:params), :remote => true %>

Here is a dead easy sample https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy

这是一个非常简单的示例https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy

回答by Richard Peck

HTML

HTML

Looks like the problem is you're sending an HTMLrequest for whatever reason:

看起来问题是您HTML出于任何原因发送请求:

Oweb::MainController#setmagasinstatus as HTML

Oweb::MainController#setmagasinstatus 作为 HTML

I'd surmise the "unkown format" error will therefore be caused by your lack of definition for the htmlmime-type in your action. I'd imagine this would work to resolve the error at surface-level:

因此,我推测“未知格式”错误是由于您在操作中缺乏对htmlmime 类型的定义造成的。我想这将有助于解决表面级别的错误:

 respond_to do |format|
     format.js 
     format.html
  end


Ajax

阿贾克斯

If the above is correct, the question then turns to "why is an HTML mime-type being sent?"

如果以上是正确的,那么问题就会变成“为什么要发送 HTML MIME 类型?”

Due to not being able to see your actual Ajax code, I'd recommend the problem will eitherbe that you're just sending a standard HTTP request (ajax is XHR); or you'll have an issue with the declaration with the ajax request

由于无法看到您的实际 Ajax 代码,我建议问题要么是您只是发送标准 HTTP 请求(ajax 是XHR);否则您的 ajax 请求声明会出现问题

You must remember that Ajax (Asynchronous Javascript And XML) is meant to send a request on your behalf -- like a pseudo browser. This means if you want to send an ajax request, it has to be done through Javascript (hence the format.jsmime type handler)

您必须记住,Ajax(Asynchronous Javascript And XML)旨在代表您发送请求——就像一个伪浏览器。这意味着如果你想发送一个 ajax 请求,它必须通过 Javascript 完成(因此是format.jsmime 类型处理程序)

--

——

Personally, I think you're not sending an ajax request, although it could also be that you're sending a different dataType, such as JSON

就个人而言,我认为您没有发送 ajax 请求,尽管也可能是您发送了不同的dataType,例如JSON