尽管准备好页面,Rails javascript仍未触发:加载

时间:2016-08-02 21:42:58

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

我正在使用带有rails的条带,并且每当我刷新页面时,ajax调用似乎都能正常工作。我相信这是turbolinks的问题,'ready page:load'不能像我预期的那样工作。

以下是该卡的表格:

<%= form_tag subscribers_path, id:'subscriber_form' do %>
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title">Add Card</h4>
    </div>
    <div class="modal-body">

      <div class="field">
        <%= label_tag :"Card Number" %>
        <%= text_field_tag nil, nil, "data-stripe":"number", size:"20" %>
      </div>


      <div class="field">
        <%= label_tag :"Expiration Date" %>
        <%= text_field_tag nil, nil, "data-stripe":"exp_month", size:"2" %>/
        <%= text_field_tag nil, nil, "data-stripe":"exp_year", size:"2" %>
      </div>

      <div class="field">
        <%= label_tag :"CVC" %>
        <%= text_field_tag nil, nil, "data-stripe":"cvc", size:"4" %>
      </div>



    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <%= submit_tag "Add card", class:"btn btn-primary submit", id:"card_submit_button" %>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<% end %>

和Javascript:

$(document).on('ready page:load', function () { 


  $('#subscriber_form').submit(function(event) {
    var $form = $(this);

    console.log($form);
    $form.find('.submit').prop('disabled', true);
    $form.find('.submit').val('loading...');

    Stripe.card.createToken($form, stripeResponseHandler);
    return false;
  });

var stripeResponseHandler = function(status, response) {
    var $form = $('#subscriber_form');

    if (response.error) {
      $form.find('.payment-errors').text(response.error.message);
      $form.find('button').prop('disabled', false);
      $form.find('.submit').val('submit');
    } else {
      $form.append($('<input type="hidden" name="stripeToken" />').val(token));

      var dataSet = $form.serialize();
      $.ajax({
        type: "POST",
        url: $form.attr("action"),
        data: dataSet,
        dataType: "script",
        complete: function(){
          $form.get(0).reset();
          console.log(response);
          $('#card_select input:last').prop("checked", "checked");


          $('#cardModal').modal('hide')

          $form.find('.submit').prop('disabled', false);
          $form.find('.submit').val('Add card');

        },
        error: function(exception){console.log("exception" + exception);}
      });
    }
  };


});

当我点击指向该页面的链接时,该脚本仍无效。

1 个答案:

答案 0 :(得分:1)

据我所知,没有。(准备好&#39;)所以也许你应该尝试类似的方法:

var stripe;

stripe = function() {...};

$(document).ready(stripe);

$(document).on('page:load', stripe);