Rails的简单例子3 +使用UJS Ajax来进行远程调用和渲染生成的JSON对象 [英] Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object

查看:94
本文介绍了Rails的简单例子3 +使用UJS Ajax来进行远程调用和渲染生成的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一些Ajax功能在我的Rails 3应用程序。

I'm trying to add some Ajax functionality in my Rails 3 app.

具体而言,我希望有一个按钮,将提交一个Ajax请求调用远程函数在我的控制器,随后查询的API,并返回一个JSON对象的页面。

Specifically, I want a button that will submit an Ajax request to call a remote function in my controller, which subsequently queries an API and returns a JSON object to the page.

在我收到的JSON对象我想要显示的内容。

Once I receive the JSON object I want to display the contents.

所有这些都与新的Rails 3 UJS的方法了。 是否有一个很好的例子/教程本次网上某处?的我一直没能找到一个对谷歌。用一个按钮为切入点,一个简单的例子(即用户点击按钮启动该进程)会的工作了。

All of this with the new Rails 3 UJS approach, too. Is there a good example/tutorial for this online somewhere? I haven't been able to find one on google. A simple example using a button as the entry point (ie, the user clicks the button to start this process) would work, too.

修改 让我尝试用不同的方法。我想有这个按钮查询外部API,它返回的JSON,并显示在页面上的JSON。我不知道在哪里甚至开始。难道按钮本身查询外部API?我是否需要经过控制器,并有控制器查询外部API,得到JSON,并给予JSON回到这个网页?如何显示/上网本JSON的内容是什么?老实说,我无法找到JSON

Edit Let me try this with a different approach. I want to have this button query an external API, which returns JSON, and display that JSON on the page. I have no idea where to even begin. Does the button itself query the external API? Do I need to go through the controller, and have the controller query the external API, get the JSON, and give the JSON back to this page? How do I display/access the contents of this JSON? I honestly can't find a good Rails 3.x example of how to handle JSON...

推荐答案

下面是一个开始:

首先,在您的视图中的link_to方法创建按钮,例如:

First create your button with a link_to method in your view, for example:

=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'

请注意,我追加.json我的资源​​的URL。这是一个一个AJAX删除,谷歌的link_to看到参数的含义的只是一个例子。这个概念如果你与参数的HTTP请求:远程设置为true,换句话说,这是翻译从浏览器的AJAX调用

Note that I am appending ".json" to the url of my resource. This is just an example of a an AJAX delete, google link_to to see the meaning of the parameters. The concept if that you make your HTTP request with the parameter :remote set to true, in other words this is translated to an AJAX call from your browser.

二,写一些JavaScript代码,以便您可以处理什么都是AJAX的结果叫你的浏览器将当第1步细节的的link_to用户点击就可以看到这个博客帖子:的 http://www.alfajango.com/blog/rails-3-remote-联系-和表单/

Second, write some javascript so that you can process what ever is the result of the AJAX call your browser will make when the user click on the link_to of step 1. For details you can see this blog post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

从我的网站的一个例子:

An example from my site:

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#pending_invitation")
    .live("ajax:loading",  toggleLoading)
    .live("ajax:complete", toggleLoading)
    .live("ajax:success", function(event, data, status, xhr) {
       var response = JSON.parse(xhr.responseText)
       if (response.result == "ok") {
          $(this).fadeOut('fast');
       }
       else {
         var errors = $('<div id="error_explanation"/>');
         errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
         $('#new_invitation_error').append(errors)   
       }
    });
});

在这里你可以看到,我解析返回的JSON和和改变HTML基础上的网页上。请注意,这个js使用在这里不包括在顶视图中定义的CCS ID和班级。

where you can see that I parse the returned json and and change the html on the page based on that. Note that this js uses the CCS ids and classes defined in the top view that is not included here.

如果您现在要你写自己的控制器吐出来这里的JSON是一个例子:

If you now want to write you own controller to spit out the json here is an example:

class InvitationsController < ApplicationController
  respond_to :html, :json

  # other methods here
  # ...

  def destroy
    @invitation = Invitation.find(params[:id])
    respond_to do |format|
      if @invitation
        @invitation.destroy
        flash[:success] = I18n.t 'invitations.destroy.success'
        format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
      else
        format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
      end
    end
  end
end

希望这有助于。

Hope this help.

这篇关于Rails的简单例子3 +使用UJS Ajax来进行远程调用和渲染生成的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆