How to render a partial from controller after making an ajax call

我只是一个虾纸丫 提交于 2020-01-05 08:04:58

问题


I am trying to render a partial after I make an AJAX request to a method in my controller. Here is my current AJAX call:

$('.savings_link').click(function(event){
 $.ajax({
    type: 'GET',
    url: '/topics/savings_easter_egg',
    data: {
      savings: data[key]['saving']
    } ,
    dataType: 'json',
  });

 event.preventDefault(); // Prevent link from following its href
});

This call currently works and it hits my controller method where I try to return and render a partial.

def savings_easter_egg
  @savings = params[:savings] if params[:savings]

  return render :json => {
    :html => render_to_string({
      :partial => "topics/savings",
      :locals => { :savings => @savings }
    })
  }
end

Using firebug, I was able to get the response:

{"html":"<p>Hi</p>"}

which reflects my partial topics/savings, but the page does not reload or display my partial.

However, I want to actually redirect or render (display) the actual partial. Any advice?


回答1:


you code should be like this

$.ajax({
 type: 'GET',
 url: '/topics/savings_easter_egg',
 data: {
  savings: data[key]['saving']
 },
dataType: 'json',
  success: function(data) {
    $('your div').html(data.html);
 }
});

you have to use that response in your success function , just add to your div done above.



来源:https://stackoverflow.com/questions/13319454/how-to-render-a-partial-from-controller-after-making-an-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!