【问题标题】:Ajax is not defined on remote_form_for在 remote_form_for 上未定义 Ajax
【发布时间】:2013-03-25 11:45:45
【问题描述】:

我在提交表单时遇到错误。这种形式定义为:

<% remote_form_for @my_object do |f| %>
  ...
<% end %>

生成的 HTML 是:

<form action="/my_objects" id="new_my_object" method="post"
   onsubmit="new Ajax.Request('/customers', {
      asynchronous:true,
      evalScripts:true,
      parameters:Form.serialize(this)
   }); return false;">
   ...
</form>

我遇到了这个 JS 错误:

Uncaught ReferenceError: Ajax is not defined 

我在某处读到这是一个原型错误,但我不明白我犯的错误。

我的配置是 Rails 2.3.16、Ruby 1.8.6、jquery 1.9.1 和 jquery-ui 1.10.2。

【问题讨论】:

  • 您正在使用 Prototype 语法,但仅包含 jQuery。切换到使用 Prototype 或使用 jQuery 方法编写 ajax 调用。
  • @Juhana 我没有使用原型语法:Rails 做到了。如何对 Rails 说“使用 jQuery 语法”?

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


【解决方案1】:

默认情况下,rails 2.x(及更早版本),为 Prototype 生成 JS 代码(参见 javascript_helperprototype_helper

要在 Rails 2.x 中生成 jQuery 代码,为 rails 2.x 添加 jrails 插件,您将能够使用相同的 rails 助手,如 remote_form_for 或 link_to_remote 和 jQuery。

jrails.js 的这一部分可能在 jquery 1.9 中已过时:

(function($) {
  $.ajaxSettings.accepts._default = "text/javascript, text/html, application/xml, text/xml, */*";
})(jQuery);

用这个代码替换它:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) { 
  options.beforeSend = function () {
    jqXHR.setRequestHeader("accept", '*/*;q=0.5, ' + $.ajaxSettings.accepts.script);
    if ($.isFunction(originalOptions.beforeSend)) originalOptions.beforeSend();
  };
});

在控制器中进行 ajax 请求检测:

def my_action
  respond_to |format|
    format.js { ... }
    format.html { ... }
  end
end

【讨论】:

  • 很高兴看到您对问题的巨大改进!为它 +1。
【解决方案2】:

如果你想使用 JQuery 试试这个:

<%= form_for @my_object, :html => {:method => "post" }, :remote => true do |form| %>

<% end %>

请同时查看 Rails 指南:http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

【讨论】:

    【解决方案3】:

    我知道这不能解决您的问题。但是我使用 JQuery AJAX 而不是 Rails remote attribute 来避免这些类型的混淆。将 AJAX 与 JQuery 结合使用非常方便。

    <% form_for @my_object do |f| %>
      ...
    <% end %>
    
    <script>
      $(function(){
        $('#form_id').submit(function(){
          $.post($(this).attr('action'), $(this).serialize(), function(data, status){
            alert(status)
          }) 
        })
      });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2011-04-22
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2014-08-20
      • 2021-10-28
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多