简体   繁体   English

Ruby On Rails jQuery AJAX Post

[英]Ruby On Rails jQuery AJAX Post

Ok, in PHP I can do this in 5 minutes. 好的,在PHP中,我可以在5分钟内完成。 With Rails I am completely lost. 有了Rails,我完全迷失了。 I am so new to Rails and I have a requirement to do more advanced stuff with it then I am comfortable with currently. 我是Rails的新手,我需要用它来做更高级的东西然后我现在很舒服。 The Big guy decided lets go Rails from PHP. 大家伙决定让我们从PHP转到Rails。 So its crash course learning. 所以它的速成课程学习。 Fun times.. 娱乐时间..

I understand from the javascript side making the post/get with jquery remains the same. 我从javascript方面了解到使用jquery发布/获取仍然是一样的。 On the ruby side however I am completely lost. 然而在红宝石方面,我完全迷失了。 What do I need to do in order to do a post/get to a Rails App. 我需要做什么才能发布/获取Rails应用程序。 How would I define my controller? 我该如何定义我的控制器? Lets say from the HTML side I am posting 让我们从HTML方面说我发布

input1 and input2 standard jquery $.post with a JSON request for data back. input1和input2标准jquery $ .post,带有JSON数据请求。 With php I would make a simple controller like: 使用php我会做一个简单的控制器,如:

public function myFormPostData(){
    $errors = "none";
    $errorMsg = "";
    if($_POST['input1'] == ""){$errors = "found"; $errorMsg .= "Input 1 Empty<br>";}
    if($_POST['input2'] == ""){$errors = "found"; $errorMsg .= "Input 2 Empty<br>";}

    if($errors == "found"){ $output = array("error" => "found", "msg" => $errorMsg); }
    else{
        $output = array("error" => "none", "msg" => "Form Posted OK!!"); 
    }
  echo json_encode($output);
}

but in ruby I dunno how to translate that concept. 但在红宝石中,我不知道如何翻译这个概念。 I'm open to suggestions and good practices. 我愿意接受建议和良好做法。 Grant it the above is a super mediocre rendition of what I am needing to do I would sanitize things more than that and all else, but it gives the idea of what I am looking for in Rails.. 授予它以上是我需要做的超级平庸的演绎我会更多地清理事物而不是其他所有事情,但它给出了我在Rails中寻找的想法。

First, you need to tell Rails that a certain page can accept gets and posts. 首先,您需要告诉Rails某个页面可以接受获取和发布。

In your config/routes.rb file: 在config / routes.rb文件中:

get 'controller/action'
post 'controller/action'

Now that action in that controller (for example, controller "users" and action "index") can be accessed via gets and posts. 现在可以通过获取和发布来访问该控制器中的操作(例如,控制器“用户”和操作“索引”)。

Now, in your controller action, you can find out if you have a get or post like this: 现在,在您的控制器操作中,您可以查看是否有这样的获取或发布:

def index
    if request.get?
        # stuff
    elsif request.post?
        # stuff
        redirect_to users_path
    end
end

Gets will look for a file corresponding to the name of the action. 获取将查找与操作名称对应的文件。 For instance, the "index" action of the "users" controller will look for a view file in app/views/users/index.html.erb 例如,“用户”控制器的“索引”操作将在app/views/users/index.html.erb查找视图文件

A post, however, is usually used in conjunction with the redirect (like in the above example), but not always. 但是,帖子通常与重定向一起使用(如上例所示),但并非总是如此。

First of all, Rails 3 has a nice feature called respond_with . 首先,Rails 3有一个很好的功能叫做respond_with You might check out this Railscast episode that talks about it. 你可以看看这个谈论它的Railscast剧集。 http://railscasts.com/episodes/224-controllers-in-rails-3 . http://railscasts.com/episodes/224-controllers-in-rails-3 The examples he uses are great if you are dealing with resources. 如果你正在处理资源,他使用的例子很棒。

Having said that, I'll give you an example with a more traditional approach. 话虽如此,我会举一个更传统方法的例子。 You need to have a controller action that handles requests which accept JSON responses. 您需要有一个控制器操作来处理接受JSON响应的请求。

class MyController < ApplicationController
  def foo
    # Do stuff here...
    respond_to do |format|
      if no_errors? # check for error condition here
        format.json { # This block will be called for JSON requests
          render :json => {:error => "none", :msg => "Form Posted OK"}
        }
      else
        format.json { # This block will be called for JSON requests
          render :json => {:error => "found", :msg => "My bad"}
        }
      end
    end
  end
end

Make sure that you have a route set up 确保您已设置路线

post '/some/path' => "my#foo"

Those are the basics that you will need. 这些是您需要的基础知识。 Rails gives you a lot for free, so you may find that much of what you are looking for already exists. Rails为您提供了大量免费服务,因此您可能会发现您所寻找的大部分内容已经存在。

If you post a more concrete example of what you are trying to you might get even better advice. 如果你发布一个更具体的例子,你可能会得到更好的建议。 Good luck! 祝好运!

its hard at first to understand that you have to do things "the rails way", because the whole philospohy of rails is to enforce certain standards. 一开始很难理解你必须做“铁路方式”,因为轨道的整体哲学是强制执行某些标准。 If you try to fit PHP habits in a rails suit, it will just tear apart. 如果你试图将PHP习惯融入铁轨套装中,它就会撕裂。 The Rails Guides are your best friend here... Rails指南是你最好的朋友......

To be more specific about your problem, you should try to build something from ActiveModel . 要更具体地解决您的问题,您应该尝试从ActiveModel构建一些东西。 ActiveModel lets you use every feature ActiveRecord has, except it is meant to be used to implement non-persistent objects. ActiveModel允许您使用ActiveRecord具有的每个功能,除非它用于实现非持久对象。

So you can create, say, a JsonResponder model: 所以你可以创建一个JsonResponder模型:

class JsonResponder
  include ActiveModel::Validations

  validates_presence_of :input_1, :input_2

  def initialize(attributes = {})
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end
end

In your controller, you now create a new JsonResponder : 在您的控制器中,您现在创建一个新的JsonResponder:

 # this action must be properly routed, 
 # look at the router chapter in rails 
 # guides if it confuses you
 def foo 
     @responder = JsonResponder.new(params[:json_responder])

     respond_to do |format|
       if @responder.valid?
          # same thing as @wizard's solution
          # ...
       end
     end
 end

now if your your input fields are empty, errors will be attached to your @responder object, same as any validation error you can get with an ActiveRecord object. 现在,如果您的输入字段为空,则错误将附加到您的@responder对象,与使用ActiveRecord对象可以获得的任何验证错误相同。 There are two benefits with this approach : 这种方法有两个好处:

  • all of your logic is kept inside a model of its own. 你的所有逻辑都保存在自己的模型中。 If your response has to be improved later (process a more complicated request for instance), or used from different controllers, it will be very simple to reuse your code. 如果您的响应必须稍后改进(例如处理更复杂的请求),或者从不同的控制器使用,则重用代码将非常简单。 It helps keeping your controllers skinny , and thus is mandatory to take a real advantage out of MVC. 它有助于保持控制器的瘦 ,因此必须从MVC中获得真正的优势。

  • you should be able (maybe with a little tweaking) to use rails form helpers, so that your form view will only have to be something vaguely like this : 你应该能够(可能需要稍微调整一下)使用rails form helper,这样你的表单视图只需要像这样模糊:

(in the equivalent of a "new" View) (相当于“新”视图)

<% form_for @responder do |f| %>
   <%= f.input_field :field_1 %>
   <%= f.input_field :field_2 %>
   <%= f.submit %>
 <% end %>

feel free to ask for more precisions. 随意要求更多的精确度。

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

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