【问题标题】:Rails 4 loads JS as plain text when trying to use AJAXRails 4 在尝试使用 AJAX 时将 JS 加载为纯文本
【发布时间】:2015-07-12 18:17:15
【问题描述】:

我正在尝试创建一个包含两列的简单页面。在左栏中,用户可以填写表格。在提交表单时,我希望右列刷新(通过 AJAX)并使用在控制器中创建的 @url 字符串填充 div。现在,表单提交根本不会触发我的 .js 页面上的代码——相反,它会重定向离开页面并将我的 .js 作为纯文本加载到浏览器中。这应该很简单——我做错了什么?

在配置/路由中:

    root 'home#home'
    post '/pixify', to: 'home#pixify', as: "pixify",  format: 'js'

在 HomeController 中:

    class HomeController < ApplicationController
      respond_to :html, :js
      skip_before_action :verify_authenticity_token

      def home
      end

      def pixify
        @url = "http://example-url.com"
        respond_to do |format|
          format.js { render :layout => false }
        end
      end
    end

在views/home/home.html.haml中:

   %div#container
     %div.left-column
       = form_tag pixify_path, :remote => true do
         %fieldset
            %ul
                %li
                    %label{:for => "url-id"} URL ID:  
                    %input{:type => "text", :name => "url-id"}

            %input{:type => "submit", :value => "Generate url", :class => "button"}

     %div.right-column
       %div#generated-url

在views/home/pixify.js.erb:

    console.log("This is working");   // but it isn't
    $('#generated-url').html('http://www.justanexample.com');

【问题讨论】:

  • 检查表单的输出HTML,它应该有data-remote="true",另外,你需要包含rails附带的jquery-ujs脚本。
  • HTML 输出确实有 data-remote="true"require jquery' and require jquery_ujs` 在 application.js 中是必需的。还有其他建议吗?
  • @seesarahcode - 您可以尝试从路由中删除 format: 'js' 选项并从控制器中删除 render :layout =&gt; false 吗?
  • @VenkatCh 如果我删除这两行(或仅删除 format: 'js' 行),我会在 home#pixify 操作中的响应块中收到 ActionController::UnknownFormat 错误。如果我删除 render :layout =&gt; false 行,我不会收到任何错误,但它仍会将我的 .js 文件呈现为纯文本。是否有其他组合可能有效?
  • @seesarahcode - 请再做一次调试.. 即从控制器评论respond_to :html, :js 并尝试? (yn) 如果它不起作用,请尝试提供您的控制台输出请求?

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


【解决方案1】:

如果您的 application.js 文件中没有 jquery_ujs 库,js.erb 文件将呈现为文本:

//= require jquery
//= require jquery_ujs

我敢打赌,这就是“默认”文件和“应用程序”文件之间的区别。

您的 gemfile 中需要以下 gem:

gem 'jquery-rails'
gem 'jquery-ui-rails'

【讨论】:

  • 只需在 application.js 中添加 //= require jquery_ujs 即可在 rails 5 中为我修复此问题。似乎不需要 gem 'jquery-ui-rails'
【解决方案2】:

我想通了! This answer 让我走上正确的道路。由于 application.html.erb 中的 javascript 标记,jquery_ujs 无法正常工作。原来我需要改变这个:

&lt;%= javascript_include_tag :defaults %&gt;

到这里:

&lt;%= javascript_include_tag 'application' %&gt;

我在对单独的模板问题进行故障排除时更改了该行,但忘记将其切换回来。我还从控制器中删除了渲染语句(根据@VenkatCh 的回答——谢谢!),现在一切正常。

respond_to do |format| format.js end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多