Why is Rails UJS ajax:success bind being called twice?

独自空忆成欢 提交于 2019-11-30 05:44:54

问题


I have a simple form:

= form_for(posts_path, :id => "new_post", :remote => true) do
  = text_field_tag "post[input]"
  = submit_tag "Post!"

I have bound a callback to the ajax:success event:

$("form#new_post").bind("ajax:success", function(xhr, data, status){
  alert("Post Created!");
});

When I click the Post! button, the Post Created comes up twice. Why?

I'm using Rails 3.1 which by default is using jquery-ujs.


回答1:


That is because your page is loading jquery_ujs code twice in development mode when precompiled assets exist in /public/assets.

In development mode javascript requries are loaded with separate tags: jquery, jquery_ujs.js, myscripts.js and finally applications.js. The problem happens when precompiled application.js exists and is used from /public/assets - it contains compilation of all previous files. This is triggered by assets:precompile rake task.

The solution is to remove /public/assets directory on development then application.js is used (from /app/assets/javascript) which doesn't include previous files. Generally doesn't use assets:precompile rake task on development.

Update

Adding config.serve_static_assets = false to development.rb also solves problem for me without worrying about /public/assets.




回答2:


A similar thing happened to me upgrading an application from Rails 3.0 to 3.1, it was my mistake. In your

app/assets/javascripts/application.js

check that your are not calling twice the rails helpers, i have troubles using

//= require_tree .

i have removed this and just left

//= require jquery
//= require jquery_ujs
//= require myscripts

i deleted too app/assets/javascripts/rails.js, the file was generated by jquery-rails gem but this is no longer necessary




回答3:


For me the gotcha was the

config.assets.debug = true

option.



来源:https://stackoverflow.com/questions/7225600/why-is-rails-ujs-ajaxsuccess-bind-being-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!