javascript 对 Rails 中的控制器动作进行 ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17344045/
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-10-27 07:57:57  来源:igfitidea点击:

making an ajax call to controller action in rails

javascriptruby-on-railsajax

提问by nicosantangelo

I am trying to make an ajax call to my controller

我正在尝试对我的控制器进行 ajax 调用

class PatientRecordController < ApplicationController
  def export
     ....
  end
end

In my javascript file i have

在我的 javascript 文件中,我有

$(document).ready(function(){
    freezeTopRow($('#dataTable'));
    $("#export").click(function(){
        $.ajax({url: "patient_record/export", type: "POST"});
    });
});

when i inspect element and debug and when i click the export tag on my page. i hit the function however it never gets to the controller

当我检查元素和调试时以及当我单击页面上的导出标记时。我点击了这个功能,但它永远不会到达控制器

Also I have 2 controllers and 2 views. In my other controller and view I do the same thing and it works

我还有 2 个控制器和 2 个视图。在我的另一个控制器和视图中,我做同样的事情并且它有效

回答by nicosantangelo

Have you checked that you routes.rbhave something like:

你有没有检查过你routes.rb有类似的东西:

post 'patient_record/export'

Maybe Rails doesn't know the route so the ajax isn't working (if you can get to the action from your browser it means that you have only a GETset, you can check that changing the type of the request in the ajax call)

也许 Rails 不知道路由,所以 ajax 不起作用(如果您可以从浏览器获取操作,则意味着您只有一个GET集合,您可以检查更改 ajax 调用中的请求类型)

回答by pjmorse

You also need a route for the exportaction in your config/routes.rbfile, something like

您还需要文件中export操作的路由config/routes.rb,例如

resources :patient_records do
  member do
    post :export
  end
end

You can check to see if this already exists by running rake routes | grep 'export'.

您可以通过运行来检查它是否已经存在rake routes | grep 'export'