为什么 Rails UJS ajax:success bind 被调用两次?
我有一个简单的表单:
= form_for(posts_path, :id => "new_post", :remote => true) do
= text_field_tag "post[input]"
= submit_tag "Post!"
我已将回调绑定到 ajax:success
事件:
$("form#new_post").bind("ajax:success", function(xhr, data, status){
alert("Post Created!");
});
当我单击 Post!
按钮时,Post Created
出现两次。为什么?
我正在使用 Rails 3.1,默认情况下使用 jquery-ujs。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为当
/public/assets
中存在预编译资源时,您的页面会在开发模式下加载jquery_ujs
代码两次。在开发模式下,JavaScript 需求使用单独的标签加载:
jquery
、jquery_ujs.js
、myscripts.js
以及最后的applications.js< /代码>。当预编译的
application.js
存在并从/public/assets
使用时,就会出现问题 - 它包含所有先前文件的编译。这是由assets:precompile
rake 任务触发的。解决方案是在开发时删除
/public/assets
目录,然后使用application.js
(来自/app/assets/javascript
),这不会不包括以前的文件。在开发中通常不使用
assets:precompile
rake 任务。更新
将
config.serve_static_assets = false
添加到development.rb
也为我解决了问题,而不必担心/public/assets
>。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 finallyapplications.js
. The problem happens when precompiledapplication.js
exists and is used from/public/assets
- it contains compilation of all previous files. This is triggered byassets:precompile
rake task.The solution is to remove
/public/assets
directory on development thenapplication.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
todevelopment.rb
also solves problem for me without worrying about/public/assets
.我将应用程序从 Rails 3.0 升级到 3.1 时也发生了类似的事情,这是我的错误。在你
检查你没有调用两次rails助手时,我在使用时遇到了麻烦,
我已经删除了这个,只是留下了
我也删除了
app/assets/javascripts/rails.js
,该文件是由jquery生成的-rails gem 但这不再是必要的A similar thing happened to me upgrading an application from Rails 3.0 to 3.1, it was my mistake. In your
check that your are not calling twice the rails helpers, i have troubles using
i have removed this and just left
i deleted too
app/assets/javascripts/rails.js
, the file was generated by jquery-rails gem but this is no longer necessary对我来说,陷阱就是一个
选择。
For me the gotcha was the
option.