开发者

Get data back from controller method or helper in rails 3 to ajax

开发者 https://www.devze.com 2023-02-06 02:21 出处:网络
I have a following javascript that I call from my _form.html.erb. $.ajax({ type: \"GET\", url: \"/articles/\" + $(thi开发者_开发百科s).attr(\'value\'),

I have a following javascript that I call from my _form.html.erb.

$.ajax({
type: "GET",
url: "/articles/" + $(thi开发者_开发百科s).attr('value'),
success: function(data){}
});

I would like to get some kind of data back (maybe json object or Article object) from this request. I am not sure if I need to call a helper or not. When I do call a controller, all it returns me back is the html response from corresponding view.


You should probably use the respond_to block in your controller to generate different responses depending on the format.

def show
  @article = Article.find(params[:id])
  respond_to do |format|
    format.html
    format.json { render :json => @article }
  end
end

That way the template will be rendered for all standard request with html headers but if you send an ajax request with json headers, it will render the article parsed to json.

Update:

Use the following ajax call to specify json as expected response:

$.ajax({
    type: "GET",
    dataType: "json",
    url: "/articles/" + $(this).attr('value'),
    success: function(data){}
});


Another example with params:

JS:

$( "#booking_addr_edit" ).click(function(event) {
          var addressid = $('#appointment_order_currentaddress').val();
            $.ajax({
              type: "GET",
              dataType: "json",
              data: {address_id: addressid},
              url: '/booking/get_client_address',
              success: function(data){
                $('#appointment_order_address').val(data[0].street +' '+ data[0].city + ' ' + data[0].state);
                $('#appointment_order_phone').val(data[0].phone);
                $('#appointment_order_apartment').val('');
                $('#booking_client_details').show();
              }
            });  
            event.preventDefault();
        });

Controller

  def get_client_address
    @address = Address.where(id: params[:address_id])
    respond_to do |format|
      format.js { render :json => @address }
    end
  end

Routes

 match "booking/get_client_address" => "booking#get_client_address"
0

精彩评论

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