简体   繁体   English

Rails-来自JavaScript的呼叫控制器

[英]Rails - call controller from javascript

Extreme rails nooby here. 极端的轨道nooby在这里。 I am trying to do a simple call to a controller from a javascript file and am fairly stuck, research says I need a ajax request. 我正在尝试从javascript文件向控制器进行简单调用,并且陷入了困境,研究表明我需要ajax请求。 Can you guys point me in the right direction? 你们能指出我正确的方向吗?

Here is my controller - It simply returns a boolean 这是我的控制器-它只是返回一个布尔值

class ReferredFriend < ActiveRecord::Base

def refer_email_exists(email)
/return a boolean

Here is my javascript - obviously incorrect syntax, but you get my general idea 这是我的JavaScript-语法显然不正确,但是您可以理解我的一般想法

if ReferredFriend.refer_email_exists(message.get('to_email')) == 'true'
  alert "That email already exists!"

the route to the controller is: app/models/referred_friend.rb 到控制器的路由是:app / models / referred_friend.rb

I put this in my routes file, however I'm guessing this is incorrect as well 我把它放在路由文件中,但是我猜这也是不正确的

resources :referred_friends do
  get :refer_email_exists
end

Thanks for your help! 谢谢你的帮助!

The way to do want you want is make a ajax call to your route, something like: 想要的方式是对您的路线进行ajax调用,例如:

$.ajax({
  url: "<url route to refer_email_exists>",
  success: function(result){
  // check result then
  alert "That email already exists!"
  }
});

What about simple AJAX call? 简单的AJAX调用呢?

$.ajax({
    url: Routes.test_email_path(email),
    type: 'POST'
}).done(function (data) {
    // handling success
}).fail(function (data) {
    // handling failure
}   

Where Routes is from js-routes gem. 路由来自js-routes gem。

Rails provides button shortcodes for remote actions like calling a Rails controller action VIA AJAX. Rails为远程操作提供了按钮短代码,例如通过AJAX调用Rails控制器操作。 From the Rails docs http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#link-to 从Rails文档http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#link-to

link_to is a helper that assists with generating links. link_to是一个帮助生成链接的助手。 It has a :remote option you can use like this: 它具有:remote选项,您可以像这样使用:

<%= link_to "an article", @article, remote: true %>

which generates: 产生:

<a href="/articles/1" data-remote="true">an article</a>

You can bind to the same Ajax events as form_for. 您可以绑定到与form_for相同的Ajax事件。 Here's an example. 这是一个例子。 Let's assume that we have a list of articles that can be deleted with just one click. 假设我们有一个列表,只需单击一下即可删除。 We would generate some HTML like this: 我们将生成一些这样的HTML:

<%= link_to "Delete article", @article, remote: true, method: :delete %> and write some CoffeeScript like this:

$ -> $("a[data-remote]").on "ajax:success", (e, data, status, xhr) -> alert "The article was deleted."

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

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