【问题标题】:Rails - make link work with ajaxRails - 使链接与 ajax 一起工作
【发布时间】:2014-01-25 18:14:08
【问题描述】:

我有一个链接应该使用 ajax 来加载它旁边的部分而不重新加载页面。这是链接:

<%= link_to 'test ajax link', profile_form_path , remote: true %>

这是链接应该转到的控制器:

class ProfilesController < ApplicationController
    def profile_form #the action is currently static so there is nothing in the controller
    end
end

这里是控制器动作的 js 视图:
profile_form.js.erb

$('.tab-edit-profile').html("<%= j render 'profile_form_p' %>");

但是,它不起作用。浏览器返回此错误:

Template is missing
Missing template profiles/profile_form

这是路由文件中的一行:

get 'profile_form', to: 'profiles#profile_form'

如果我将文件名更改为 profile_form.html.erb,页面会加载但显然不使用 ajax。谁能告诉我使用 ajax 来实现这个的正确方法?谢谢。

【问题讨论】:

  • 你能发布你的路线吗? HTTP 动词可能没有对齐。
  • 当然,刚刚发布。谢谢。
  • 你收到一个 HTML 格式的请求,并且你有一个 .js.erb 文件(ERB 文件最后生成一个 JS 文件),这就是 Rails 抱怨的原因:响应 HTML 格式,他正在寻找profile_form.html.erb。您可以创建此文件并自己插入脚本标签:&lt;script type="text/javascript"&gt;$('.tab-edit-profile').html("&lt;%= j render 'profile_form_p' %&gt;");&lt;/script&gt;
  • @MrYoshiji ,谢谢,但这不起作用,因为那样视图将不会通过 ajax 加载,整个页面将转到链接。
  • 你使用的是什么版本的 Rails?

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4


【解决方案1】:

根据您上面发布的内容,这应该可以正常工作。我能想到的唯一一件事是您没有包含所需的 javascript 库,并且 link_to 助手实际上并没有发出 AJAX 请求。

您表示您正在使用 Rails 4,所以我假设您也在使用 Asset Pipeline。请确保您的app/assets/javascripts/application.js 文件中有以下几行

//= require jquery
//= require jquery_ujs

并且 javascript 包含在 ProfilesController 使用的布局中。假设布局是application.html.erb,确保你有

<%= javascript_include_tag "application" %>

在布局的&lt;head&gt; 部分中。

【讨论】:

    【解决方案2】:

    你需要的是一个部分,例如,_profile.html.erb。下划线告诉 Rails 这个文件被渲染为部分文件。在你的profile_form.js.erb你可以试试。

    $('.tab-edit-profile').html("<%= escape_javascript(render 'profile') %>");
    

    这应该让您使用静态内容。对于动态,设置一个@profile 实例变量并尝试。

    $('.tab-edit-profile').html("<%= escape_javascript(render @profile) %>");
    

    请务必在控制器响应中使用render json: @profile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      相关资源
      最近更新 更多