如何使用ajax从javascript调用控制器函数

时间:2013-11-29 17:09:38

标签: javascript jquery ruby-on-rails redmine redmine-plugins

你好我正在尝试调用我在我的控制器上用我的javascript编写的函数,因为当我点击一个按钮时,这是一个动作。

我跟着thread,但它根本没用。当我点击按钮时,我得到下面列出的错误:

Started GET "/projects/:id/repository/:branch" for 127.0.0.1 at 2013-11-29 15:03:43 -0200
Processing by RepositoriesController#show as */*
  Parameters: {"id"=>":id", "repository_id"=>":branch"}
  ←[1m←[35m (0.0ms)←[0m  SELECT MAX(`settings`.`updated_on`) AS max_id FROM `settings`
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT `users`.* FROM `users` WHERE `users`.`type` IN ('User', 'AnonymousUser') AND `users`.`status` = 1 AND `users`.`
id` = 10 LIMIT 1←[0m
  Current user: guilherme.noronha (id=10)
  ←[1m←[35mProject Load (1.0ms)←[0m  SELECT `projects`.* FROM `projects` WHERE `projects`.`identifier` = ':id' LIMIT 1
  Rendered common/error.html.erb (1.0ms)
Filter chain halted as :find_project_repository rendered or redirected
Completed 404 Not Found in 24ms (Views: 21.0ms | ActiveRecord: 1.0ms)

我不明白为什么会收到这个错误,所以我来这里寻求帮助。

我的代码试图检测某些错误或缺少某些内容:

_view_button_release.html.erb

<script>
    function CallExec(rep) {
      $.ajax("/projects/:id/repository/:branch");
    }
</script>

<div class="contextual">
<% if User.current.allowed_to?(:exec, @project) %>
    <%= button_to_function l(:gerar_build_project), 'CallExec("'+params[:repository_id].to_s+'")' %>
|
<% end %>
</div>

的routes.rb

resources :repositories do
  match 'projects/:id/repository', :action => 'exec_client', :controller => 'repositories', :via => :post
  match 'projects/:id/repository/:branch', :action => 'exec_client', :controller => 'repositories', :via => :post
  get :exec_client, on: :collection
end

client.rb(hook)

module InstanceMethods
  require_dependency 'repositories_controller'
  def exec_client
    begin
      ...
    end
  end
end

有什么建议吗?

更新:

新日志

Started GET "/projects/b1309/repository/b1309i11/" for 127.0.0.1 at 2013-12-02 10:38:00 -0200
Processing by RepositoriesController#show as */*
  Parameters: {"id"=>"b1309", "repository_id"=>"b1309i11"}
  ←[1m←[35m (0.0ms)←[0m  SELECT MAX(`settings`.`updated_on`) AS max_id FROM `settings`
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT `users`.* FROM `users` WHERE `users`.`type` IN ('User', 'AnonymousUser') AND `users`.`status` = 1 AND `users`.`
id` = 10 LIMIT 1←[0m
  Current user: guilherme.noronha (id=10)

1 个答案:

答案 0 :(得分:0)

第一。在您的js代码中

$.ajax("/projects/:id/repository/:branch");

您需要插入而不是:id项目标识符,而不是:branch分支ID或分支名称(我不知道控制器期望的是什么)。

第二。你需要正确传递params,因为我没有看到它们中的任何一个进入日志。我看到从网址Parameters: {"id"=>":id", "repository_id"=>":branch"}中获取的参数。如何通过ajax传递params你可以google。例如,您可以查看jquery doc并找到examples