简体   繁体   English

无法通过Rails中的Ajax调用控制器方法

[英]Unable to call controller method through ajax in rails

I have tried all my googling skills , but i am not able to figure out the solution to my problem yet. 我已经尝试了所有的谷歌搜索技能,但是还无法解决问题。

I am trying to send parameter to controller method from jquery using ajax. 我正在尝试使用ajax从jquery向控制器方法发送参数。 Once method is called, it will render its respective view page. 一旦方法被调用,它将呈现其各自的视图页面。 But its not even entering into the ajax code to call the controller method(By inspect). 但是它甚至没有输入ajax代码来调用控制器方法(通过检查)。 I guess i am doing something really silly , but unable to figure out, Please help me out. 我想我做的事情确实很愚蠢,但无法弄清楚,请帮帮我。

My Controller Method code: 我的控制器方法代码:

def profile 
@prof = User.where(:id => params[:id])
end

My .js file 我的.js文件

$(document).ready(function(){
    $('.table tr').click(function(){
      $.ajax({
          url: "users/profile",
          type: "POST",
          data: {id: $(this).attr('id')},
          success: function (data) {
          alert(data);
      }
  });
});
    });

My routes file: 我的路线文件:

 resources :users, :only => [:new, :create, :index,:profile]
  match 'users/profile' => 'users#profile', :as => :profile

Try this in your routes.rb 在您的routes.rb中尝试一下

resources :users, :only => [:new, :create, :index]
get 'users/profile/:id' => 'users#profile', :as => :profile

And change your js method: 并更改您的js方法:

$(document).ready(function(){
    $('.table tr').click(function(){
      $.ajax({
          url: "/users/profile/" + $(this).attr('id'),
          type: "GET",
          success: function (data) {
              alert(data);
          }
      });
    });
  });

And your method should serialize to json, like this: 并且您的方法应序列化为json,如下所示:

def profile 
  @prof = User.where(:id => params[:id])
  respond_to do |format|
    format.json  { render :json => @proof }
  end
end

Change your js method: 更改您的js方法:

$(document).ready(function(){
    $('.tr_class').click(function(){
      $.ajax({
          url: "/users/profile?id="+$(this).attr('id'),
          type: "GET",
          success: function (data) {
             alert(data);
          }
      });
    });
  });

And your method should serialize to json, like this: 并且您的方法应序列化为json,如下所示:

def profile 
  @prof = User.where(:id => params[:id])
  respond_to do |format|
    format.json  { render :json => @proof }
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM