Rails 3 的简单示例UJS使用Ajax进行远程调用,并渲染生成的JSON对象

发布于 2024-11-03 01:26:19 字数 468 浏览 3 评论 0原文

我正在尝试在我的 Rails 3 应用程序中添加一些 Ajax 功能。

具体来说,我想要一个按钮,该按钮将提交 Ajax 请求以调用控制器中的远程函数,该函数随后查询 API 并将 JSON 对象返回到页面。

收到 JSON 对象后,我想显示内容。

所有这一切也都通过新的 Rails 3 UJS 方法实现。 网上是否有一个很好的示例/教程?我在谷歌上找不到。使用按钮作为入口点(即用户单击按钮来启动此过程)的简单示例也可以。

编辑 让我用不同的方法尝试一下。我想让这个按钮查询一个外部 API,它返回 JSON,并在页面上显示该 JSON。我不知道从哪里开始。按钮本身是否查询外部API?我是否需要通过控制器,让控制器查询外部 API,获取 JSON,然后将 JSON 返回到此页面?如何显示/访问此 JSON 的内容?老实说,我找不到一个好的 Rails 3.x 示例来说明如何处理 JSON...

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

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.

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

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.

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

合约呢 2024-11-10 01:26:20

这是一个开始:

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

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

请注意,我将“.json”附加到资源的 url 中。这只是一个AJAX删除的例子,google link_to看看参数的含义。如果您使用参数 :remote 设置为 true 发出 HTTP 请求,换句话说,这将被转换为来自浏览器的 AJAX 调用。

其次,编写一些 javascript,以便您可以处理当用户单击步骤 1 的 link_to 时浏览器将进行的 AJAX 调用的结果。有关详细信息,您可以参阅此博客文章: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

我网站上的一个示例:

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 和类,但此处未包含。

如果您现在想编写自己的控制器来吐出 json,这里有一个示例:

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

希望有所帮助。

Here is a start:

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?'

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.

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)   
       }
    });
});

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.

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.

半边脸i 2024-11-10 01:26:20

老问题,但 Ajaxifying Rails 应用程序的一个非常好的概述是:

Rails 3.1 中的 Ajax - 路线图

Old question, but a really good overview of Ajaxifying Rails applications is:

Ajax in Rails 3.1 - A Roadmap

洛阳烟雨空心柳 2024-11-10 01:26:20

另请考虑以以下格式返回错误:

render :json => @myobject.to_json, :status => :unprocessable_entity

这将确保您的客户端可以将响应作为错误处理。

Also consider returning errors in the following format:

render :json => @myobject.to_json, :status => :unprocessable_entity

This will ensure that your client can process the response as an error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文