【问题标题】:How to access Jquery's Ajax call in RoR?如何在 RoR 中访问 Jquery 的 Ajax 调用?
【发布时间】:2011-09-19 18:24:11
【问题描述】:

伙计们,我对这个 RoR 真的很陌生,此时我遇到了复杂的情况,“如何在 RoR 中使用 Jquery 的 ajax() 调用?”

我有一个控制器,叫做 Projects like this

class ProjectsController < ApplicationController
    def stagemilestone
      @milestones=Milestone.find_by_sql("SELECT name, created_at FROM milestones WHERE stage=1")
    end
end

我想从 jquery 的 ajax 调用中调用这个动作并返回数据,为此我正在使用这样的

$.ajax({
  url: "/projects/stagemilestone",
  success: function(){
   //here i need the returned data from controller
   // means output of @milestones
  }
});

所以请帮帮我,该怎么做?

【问题讨论】:

    标签: ruby-on-rails ajax jquery


    【解决方案1】:

    伙计们,我终于找到了以下解决方案并且工作得很好!!

    控制器

    def stagemilestone
        @milestones=Milestone.find(:all, :conditions => ["status_id=? and project_id=?",params[:stageid], params[:id]])
        respond_to do |format|
          format.html # index.html.erb
          format.json  { render :json => @milestones}
        end
    end
    

    而我的 char.js 看起来像这样

    $.ajax({
        type : 'get',
        url : "/projects/stagemilestone",
        data : "stageid=" + $(this).attr('name') + "&id=" + $.cookie('projectid'),    
        dataType : 'json',
        async : false,
        context : document.body,
        success : function(response) {
    
        }
      });
    

    【讨论】:

      【解决方案2】:

      我认为你想要的是使用“respond_to”

      喜欢这个

      class ProjectsController < ApplicationController
        def stagemilestone
           @milestones=Milestone.find_by_sql("SELECT name, created_at FROM milestones WHERE stage=1")
           respond_to do |format|
             format.js {render :json => @milestones}
           end
        end
      end
      

      这里有更多关于 respond_to 的信息,http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

      更新:您可能需要仔细检查 ajax 请求的接受标头(您可以查看 firebug 中的请求),您可能需要使用 format.json。请参阅此处以获取 MIME 类型的完整列表,并确保它们匹配: http://apidock.com/rails/Mime

      【讨论】:

        【解决方案3】:

        为你的成功回调添加一个参数;这将包含响应值。

         success: function(response)
         {
             // response will be the HTTP / JSON / text returned from your controller
         }
        

        【讨论】:

        • 你这样做了,但它仍然不起作用,告诉我 2 件事 1] 我需要为操作添加回报吗? say class ProjectsController return @milestones=Milestone.find_by_sql("SELECT name, created_at FROM landmarks WHERE stage=1") end end 2] 如何解析返回的数据?
        【解决方案4】:

        只需在回调函数中添加一个参数,例如:

          $.ajax({
          url: "/projects/stagemilestone",
          success: function(output){
           //Do something with 'output'
          }
        });
        

        【讨论】:

          猜你喜欢
          • 2011-12-19
          • 2013-12-15
          • 2011-08-12
          • 1970-01-01
          • 1970-01-01
          • 2011-08-14
          • 2012-11-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多