简体   繁体   English

Ruby on Rails的AJAX吗?

[英]AJAX with Ruby on Rails?

This is probably a really dumb question with a simple answer but... 这可能是一个很愚蠢的问题,答案很简单,但是...

I am working on a project where I need to use AJAX to send/receive information. 我正在一个需要使用AJAX发送/接收信息的项目中。 I am using Ruby on Rails (which I am pretty new to), but rather than using the helper methods or the built in functionality in the 'defaults' Javascript file, I need to do this manually in my own Javascript. 我使用的是Ruby on Rails(这是我的新手),但不是使用辅助方法或“默认” Javascript文件中的内置功能,而是需要在自己的Javascript中手动执行此操作。

I believe that ultimately I will want to send a request with a JSON object, then have the controller return another JSON object containing the requested information. 我相信最终我将要发送带有JSON对象的请求,然后让控制器返回另一个包含所请求信息的JSON对象。

The problem is that I cannot seem to find the syntax for sending something to a specific controller method, with parameters, directly from Javascript - everything I Google ends up being tutorials for using the Rails AJAX helper methods. 问题是,我似乎找不到直接从Javascript将参数发送到带有参数的特定控制器方法的语法-我最终将所有Google用作使用Rails AJAX帮助器方法的教程。

Depending on the version of Rails you're using, you can do the following: 根据您使用的Rails版本,可以执行以下操作:

  1. Install the jrails plugin. 安装jrails插件。 This will replace all the Prototype javascript in your application with jQuery. 这将使用jQuery替换您应用程序中的所有Prototype javascript。 This means you now have access to all the jQuery libraries, but it won't break your existing rails helper stuff (remote_form_for, etc). 这意味着您现在可以访问所有jQuery库,但不会破坏您现有的Rails帮助器内容(remote_form_for等)。

  2. Now you can use the jQuery AJAX to make any AJAX requests you want to make. 现在,您可以使用jQuery AJAX发出要发出的任何AJAX请求。 A simple example would be something like below: 一个简单的示例如下所示:

     //Let's get a specific post by id $.ajax({ type: "GET", url: "/posts/123", success: function(data){ //put the data in the DOM } }); 

Then just add the appropriate respond_to in your controller: 然后只需在控制器中添加适当的response_to即可

PostsController < ApplicationController
  def show
    @post = Post.find(params[:id)
    respond_to do |w|
      w.json { render :json => @post.to_json }
    end
  end
end

if using jQuery is an option for you, jQuery.ajax will solve your problem. 如果您选择使用jQuery ,则jQuery.ajax将解决您的问题。

[and for those who likes to say jQuery is not solution for everything, i know that. [[对于那些喜欢说jQuery并非所有解决方案的人,我都知道。 i'm just giving him an option]. 我只是给他一个选择]。

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

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