javascript函数无法在jquery-ajax中运行rails验证错误显示

Sri*_*Sri 5 jquery jquery-ui ruby-on-rails ruby-on-rails-3

我全局使用Jquery UI Datepicker函数在所有页面中使用日历.我创建了一个单独的javascript页面,如下所示:

var showDatePickers = function() {
  $('[data-field-type="date"]').datepicker({
    dateFormat: "yy-mm--dd",
    showOn: "both",
    buttonImageOnly: true,
    buttonImage: "/assets/blue-calendar-icon.png",
    buttonText: "Calendar"
  });
}

$(showDatePickers);
Run Code Online (Sandbox Code Playgroud)

我只是在我的视图中发布了我的datepicker字段,

<div class="field">
  <%= f.label :Renewal_Date %>
  <%= f.text_field :Renewal_Date, readonly: 'readonly', data: {field_type: date}}
</div>
Run Code Online (Sandbox Code Playgroud)

我将上述函数调用为单独的javascript文件.

$(function() {
  if ($('html.asset_contracts').length == 1) {
    $(document.body).on('ajax:success', '.new_asset_contract, .edit_asset_contract',     showDatePickers);
  }
});
Run Code Online (Sandbox Code Playgroud)

当页面加载,编辑和新操作时,它工作正常.但是当rails验证错误显示datepicker函数不起作用时.它显示空白text_field.

仅供参考:这是一个ajax页面,该new, create, update and edit操作正在以ajax页面形式运行.所以,我添加remote: true了我的形式,我有new.js, edit.js, create.js and update.js

这是我的控制器,

def create
     @contract = Asset::Contract.new(params[:asset_contract])

     respond_to do |format|
       if @contract.save
         format.html { redirect_to asset_contracts_path, notice: "Successfully Created" }
         format.js
         format.json { render json: @contract, status: :created, location: @contract }
       else
         format.html { render action: "new" }
         format.js
         format.json { render json: @contract.errors, status: :unprocessable_entity }
       end
     end
   end



   def update
     @contract = Asset::Contract.find(params[:id])

     respond_to do |format|
       if @contract.update_attributes(params[:asset_contract])
         format.html { redirect_to asset_contracts_path, notice: "Succesfully Updated" }
         format.js
         format.json { head :no_content }
       else
         format.html { render action: "edit" }
         format.js
         format.json { render json: @contract.errors, status: :unprocessable_entity }
       end             
     end
   end
Run Code Online (Sandbox Code Playgroud)

谢谢

cfs*_*cfs 5

你正在创建像这样的日期选择器:

$(document.body).on('ajax:success', '.new_asset_contract, .edit_asset_contract',     showDatePickers);
Run Code Online (Sandbox Code Playgroud)

但是,这只会在AJAX调用成功时运行,因此您还需要一个错误处理程序.

看来你正在使用命名空间事件,我没有看到jQuery文档中引用的那些事件.您可能希望使用全局ajax事件(例如,ajaxComplete,ajaxError等).

您需要附加一个单独的处理程序ajaxError来处理错误情况,或者只是使用该ajaxComplete事件代替ajax:success.除非你需要特定的错误处理,否则ajaxComplete就是要走的路,因为你只需要编写/维护一个处理程序.从jQuery 1.8开始,全局事件就会触发document.您需要将监听器附加到文档而不需要任何其他选择器:

$(document).on('ajaxComplete', showDatePickers);
Run Code Online (Sandbox Code Playgroud)

您可以在Ajax Events页面上阅读有关jQuery AJAX事件的更多信息.