开发者

How to access Jquery's Ajax call in RoR?

开发者 https://www.devze.com 2023-04-06 03:16 出处:网络
Guys I\'m really novice to this RoR, and at this moment i reached to complex situation that \"how to use Jquery\'s ajax() call in RoR?\"

Guys I'm really novice to this RoR, and at this moment i reached to complex situation that "how to use Jquery's ajax() call in RoR?"

I'开发者_JAVA百科ve a controller called Projects like this

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

and i want to call this action from jquery's ajax call and return the data, for this I'm using like this

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

So please help me, how to do this?


Guys finally i found Solution as Follows and working Great!!

Controller

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

and My char.js looks like this

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

    }
  });


I think what you want is to use "respond_to"

like this

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

Here's more info on respond_to, http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

UPDATE: you may want to double check the accept's header of your ajax request (you can look at the request in firebug), you may need to use format.json. Refer here for the full list of MIME types and just make sure they match up: http://apidock.com/rails/Mime


Add a parameter to your success callback; that will contain the response value.

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


Just add a parameter to the callback function, like:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号