load partial with jquery and rails

懵懂的女人 提交于 2019-11-30 18:53:26

You should not be able to access Template files (.erb) from HTTP requests, this is very bad practice. I suggest you put them outside your web servers path and access them only through your application.

I'm not sure about Rails, but I suppose you need to create a separate controller (or whatever) to do this.

EDIT this is because .erb files are Embedded Ruby files, and if you try to request them you will get all unwanted data, like <%= page_title %>, that you don't want to show the users. Therefore you need to pass these .erb files through your Rails application so that they are properly interpreted into HTML.

The reason that code doesn't work is that rails doesn't expose view files outside. To achieve the thing you want, you'll need an action which would render this partial:

def image_gallery
  render :partial => "image_gallery"
end

Also there is a plugin called jRails which replaces standard ajax helpers (which use prototype) with equivalent jquery-oriented ones. In your case you would use something like

<%= remote_function(:update => "imagecontent", :url => "/newsletters/image_gallery") %>

And even more, in Rails 3 you won't need it. See this link.

Another alternative:

$('#imagecontent').html('<%= escape_javascript render 'newsletters/image_gallery' %>');

With rails 3 you could do...

controller

@content = '/some/partial'

view - either haml.erb(html.erb) or js.erb

$('#myDiv').html("<%= escape_javascript render @content %>");

You could try this if rails 2 (only prototype available unless noConflict added)...

In the controller

@content = render :partial=>"/users/cool_partial"

Call your js

myFunction(#{@content.to_json})

Your function...

myFunction = function(content){

    $("myDiv").html(content);

}

I do agree with neutrino that this could be better handled via an action.

def get_partial
  render 'some/partial'
end

Hope this helps

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