【问题标题】:js.erb is rendering text not JSjs.erb 正在呈现文本而不是 JS
【发布时间】:2017-04-03 10:58:58
【问题描述】:

在rails中尝试通过AJAX更新搜索结果时遇到一个奇怪的问题,即在页面上的原始文本中加载<pre>标签中的js.erb,而不是触发该文件中的任何js。

在索引控制器中

if request.format.js?
    respond_to do |format|
      format.js { render layout: false }
    end
  end

表单设置为使用远程触发 AJAX:true

    = form_tag(search_path, id: "form", remote: true, :'data-type' => 'script') do

index.je.erb

alert('hello');
$("#results").innerHTML("<%= escape_javascript(render partial: 'results', locals: { results: @results } ) %>"); 

routes.rb

  match 'search', to:  'properties#index', via: :post, defaults: { format: 'js' }

在路由中,我尝试从表单中强制 js,因为以前它是 JSON,但没有区别。 从日志中,控制器正在接收 js 请求,但我在 CHrome 调试器中得到了这个:

(index):69 Resource interpreted as Document but transferred with MIME type text/javascript: "http://localhost:3000/search".

粘贴alert("Js is working") 没有问题,因此 JS 在那里并触发

我卡住了,现在应该可以正常工作了,是我错过了什么愚蠢的东西,还是我不知道的 Rails 5 中的新东西?

如果我可以提供更多信息来帮助您阻止我,请尽管问!

提前致谢

【问题讨论】:

    标签: javascript ajax ruby-on-rails-5


    【解决方案1】:

    那好吧。 'remote: true' 似乎还不够!貌似是向控制器提交ajax请求,但是控制器确定是文本。

    添加

    jQuery ->
      $('#form').on "change", ->
        $.ajax '/properties/index',
        type: 'GET'
        dataType: 'script'
        data: $('form').serialize()
    

    将表单提交到纯 ajax 似乎可以解决所有问题!

    【讨论】:

      猜你喜欢
      • 2011-07-15
      • 1970-01-01
      • 2016-12-27
      • 2015-04-19
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      相关资源
      最近更新 更多