【问题标题】:How can I DRY up my Rails/AJAX/Bootstrap 3 Modal Error Handling?我怎样才能干掉我的 Rails/AJAX/Bootstrap 3 模态错误处理?
【发布时间】:2015-11-09 19:09:02
【问题描述】:

我的 Rails 应用程序中有一系列控制器,它们都在通过 Bootstrap 3 模态输入成功提交 AJAX 后呈现 create.js.erb 文件。我还按照this description here 添加了错误处理——所以当服务器返回一个无法处理的实体时,每个模式的错误都会在<span></span> 帮助块中呈现。所有这些都完美无缺。

我的问题是代码看起来不是很干。我添加到应用程序的每个新模态(我现在最多 7 个)都要求我在 Jquery/AJAX 错误处理中定位它(以我使用它的方式) - 请参见下面的代码:

$(document).ready(function(){

  $(document).bind('ajaxError', 'form#new_person', function(event, jqxhr, settings, exception){

// note: jqxhr.responseJSON undefined, parsing responseText instead
$(event.data).render_form_errors( $.parseJSON(jqxhr.responseText) );

  });

});

相关部分为$(document).bind('ajaxError', 'form#new_person', function(event, jqxhr, settings, exception){

这是针对form#new_person,我的应用程序中的每个表单都有一个。它工作正常,但似乎没有必要重复这么多,因为我在每个代码块中更改的只是选择器。

有没有一种方法可以添加到这里,我可以将每个选择器添加为列表,或者以某种方式告诉 Jquery 只触发一次 AJAXerror 调用?

【问题讨论】:

  • 你想要什么?你想在特定的 ajax 调用而不是每次调用时调用它吗?

标签: javascript jquery ruby-on-rails ajax twitter-bootstrap


【解决方案1】:

您可以像这样使用逗号分隔的组选择器:

$(document).bind('ajaxError', 'form#new_person, sel#f2, sel#f3, sel#f4',  
                                        function(event, jqxhr, settings, exception){

或制作一个var 选择器,例如:

var selectors = 'form#new_person, sel#f2, sel#f3, sel#f4';
$(document).bind('ajaxError', selectors, function(event, jqxhr, settings, exception){
//------------use it here-----^---^---^

【讨论】:

  • 完美,这正是我想要的。进行了更改,并且效果很好。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多