Rails 3 – 使用jquery ajax调用partial的link_to

我试图得到一个link_to来显示部分通过jquery ajax,但似乎无法让它工作(编辑:返回空白屏幕),我不知道我错过了什么。 任何帮助,将不胜感激。

我想点击“预览窗口小部件”链接, 让它在div 预览中显示_widget.html.erb

根据我的理解,链接“预览小部件”应该调用动作def preview_widget ,它调用preview_widget.js.erb然后在div中呈现部分_widget.html.erb

编辑:根据Ignatius Reza的建议更新链接

show.html.erb

 'preview_widget' , :id => @widget.id, :remote => true %> %> 

widget_controller.rb

 def preview_widget respond_to do | format | format.js {render :layout => false} end end 

preview_widget.js.erb

 $( "#preview" ).html( " "widget", :locals => { :widget => @widget} ) ) %>" ); 

_widget.html.erb

  

<embed style='border: 1px solid #333333;' height='316' width='540' allowfullscreen='true' allowscriptaccess='always' type='application/x-shockwave-flash' src=''>

的routes.rb

 match 'preview_widget' => 'widgets#preview_widget' 

好的,最后得到了以下更改。
routes.rb (添加成员到窗口小部件资源)

  resources :widgets do member do get 'preview_widget' end end 

show.html.erb (更改了link_to以匹配路由)

 <%= link_to 'Preview', preview_widget_widget_path(:id => @widget.id), :remote => true %> 

现在显示部分。 我仍然不能100%确定以前的代码有什么问题 – 至少它现在有效。

在你的问题上没有清除,你“似乎无法让它工作”……但是从我给你的代码中看到的……一切似乎都是对的,但是你错过了真正的ajax调用..

它可以通过添加:remote => true添加到“预览窗口小部件”链接,例如:

 <%= link_to "Preview Widget", :action => 'preview_widget' , :id => @widget, :remote => true %> 

如果默认行为足够..或者您可以在application.js上添加自己的自定义ajax调用..

作为一个注释,我不认为设置“预览窗口小部件”链接到@widget的:id属性是明智的..因为它将放置窗口小部件的字符串表示,通常看起来像“ “也许最好把它改成”widget-link-#{@widget.id}“

我有一个类似的问题让我受到这种威胁,所以我认为在这里分享我的解决方案可能对任何人都有帮助。

使用:remote => true我得到一个正常的HTTP请求到http://localhost:3000/info/about?remote=true而不是想要的AJAX请求到http://localhost:3000/info/about

修复很容易,但很难找到!

在我的HAML视图中:

错误触发HTTP请求的代码

 = link_to( image_tag("icons/information.png", :title => t('menu.info')), :controller => "info", :action => "about", :remote => true ) 

OK-Code触发AJAX请求

 = link_to( image_tag("icons/information.png", :title => t('menu.info')), {:controller => "info", :action => "about"}, :remote => true ) 

唯一的区别是{花括号}!

有趣的是,使用AJAX请求我得到info/about.html呈现,没有布局文件。 这不是偏袒的,但接近于Jan想要的。 我期待渲染info/about.js.erb

在InfoController中

  def about respond_to do |format| format.html # renders 'views/info/about.html.erb' inside layout template on HTTP Request format.js# renders 'views/info/about.html.erb', without layout end end 

  def about respond_to do |format| format.html # => 'views/info/about.html.erb' inside layout template on HTTP Request format.js {render 'about.js'} # => renders 'views/info/about.js.erb' end end