【问题标题】:Rails `remote: true` not making AJAX requestRails `remote: true` 不发出 AJAX 请求
【发布时间】:2017-06-20 12:48:20
【问题描述】:

我的应用程序使用 Rails 5.1,每当我点击带有 link_to 和 remote: true 的 link_to 时,我都会收到 InvalidCrossOriginRequest 错误。关闭伪造保护后,应用程序最终向服务器发出完整的GET 请求并显示 javascript。

这是链接:

= link_to 'Example', example_url, remote: true

example.js.erb:

$('.example').html('alert("example message")');

路线:

scope :js, defaults: { format: :js } do
    #### Example
    get 'example', to: 'examples#example'
end

控制器:

def example
    respond_to do |format|
        format.html { redirect_to root_url, alert: 'Page not accessible' }
        format.js
    end
end

我在模板中包含了 javascript:

= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'

并且我添加了必要的js资产路径:

//= require_self

// jQuery
//= require jquery
//= require jquery_ujs

【问题讨论】:

  • 应用程序最终向服务器发出完整的 GET 请求并显示 javascript。 你希望它做什么?
  • @Pavan 它“应该”发出 AJAX 请求。 -> remote: true
  • 你提到它是显示javascript。这并不意味着它在发出 AJAX 请求?
  • 在 Rails5 中,您不再需要 //=require self 部分。所以删除它。另外,您的路线在应该是 json 时指定了 ujs 格式,对吗?你的路线应该是:范围:ujs,默认值:{格式::json}做
  • 请不要破坏您的帖子。一旦您发布了一个问题,它就属于整个 Stack Overflow 社区(在 CC BY-SA 许可下)。如果您想取消此帖子与您帐户的关联,请参阅What is the proper route for a disassociation request?

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


【解决方案1】:

您已在控制器中使用respond_to 指定格式:

respond_to do |format|
  format.js
end

【讨论】:

  • 可以用正常路由重试吗? (不在defaults: { format: :js } 范围内)
  • 我实际上都试过了。 Scoped 返回上面提到的错误,unscoped 我得到一个跨源错误 - 在关闭忘记保护后,它最终再次发出完整的 GET 请求。所以我从我开始的地方回来了。
  • (Fuu 不能在这里换行..) 嗯,奇怪,我刚刚设置了一个示例项目,它工作了,这是我的配置:application.js //= 需要 rails-ujs // = 需要 turbolinks //= require_tree . home_controller.rb class HomeController routes.rb Rails.application.routes.draw do get 'home/index' end index.html.erb index.js.erb console.log("来自 ajax 的你好");
  • 我可以看到的主要区别是我在 application.js 中的任何其他内容之前使用和加载 //= require rails-ujs
  • 这一定是format 问题。我确认,它将格式识别为html,因此它会尝试呈现相应的模板或执行我为 html 格式配置的任何操作。有没有办法强制格式为js?
【解决方案2】:

问题原来是我正在运行的一段 javascript:

e.stopPropagation();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2012-01-06
    • 1970-01-01
    • 2017-06-11
    • 2012-12-04
    相关资源
    最近更新 更多