未在remote_form_for上定义Ajax

时间:2013-03-25 11:45:45

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

我在表单提交上加了一个错误。此表单定义为:

<% 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。

3 个答案:

答案 0 :(得分:1)

默认使用rails 2.x(和早期版本),为Prototype生成JS代码(cf 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 :(得分:0)

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

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

<% end %>

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

答案 2 :(得分:0)

我知道这不是你问题的答案。但我使用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>