Rails 5.2: проблема с jQuery - PullRequest
       56

Rails 5.2: проблема с jQuery

0 голосов
/ 24 октября 2018

У меня две проблемы при использовании Ruby on Rails, Stripe gem и javascript.Во-первых, я не могу использовать Stripe API для отправки формы с информацией о кредитной карте.Во-вторых, коды в application.js не могут быть выполнены.Я думаю, что основная причина в том, что jQuery не работает над моим проектом rails.Я уже удалил турболинки, но это не работает.Пожалуйста, помогите мне!

Мой драгоценный файл

ruby '2.4.2'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.0'
# Use sqlite3 as the database for Active Record
# gem 'sqlite3'

# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
# gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false

gem 'sendgrid-ruby'
gem 'stripe'
# Image uploading
gem 'carrierwave'
# Image resizing
gem 'mini_magick'
# Authentication system
gem 'devise'
# Frontend styling
gem 'bootstrap', '~> 4.1.3'
gem 'jquery-rails'
gem 'jquery-easing-rails'
gem 'simple-line-icons-rails'
gem 'font-awesome-sass', '~> 5.3.1'

group :development, :test do
  # Use sqlite3 as the database for Active Record
  gem 'sqlite3'
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem "figaro"
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15', '< 4.0'
  gem 'selenium-webdriver'
  # Easy installation and use of chromedriver to run system tests with Chrome
  gem 'chromedriver-helper'
end

group :production do
  gem 'pg'
  gem 'rails_12factor'
  # For images in production
  gem 'fog'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Мое приложение / assets / javascripts / application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require jquery_ujs
//= require jquery3
//= require popper
//= require jquery.easing
//= require bootstrap-sprockets
//= require_tree .

$(document).on(function() {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: (target.offset().top - 48)
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

  // Closes responsive menu when a scroll trigger link is clicked
  $('.js-scroll-trigger').click(function() {
    $('.navbar-collapse').collapse('hide');
  });

  // Activate scrollspy to add active class to navbar items on scroll
  $('body').scrollspy({
    target: '#mainNav',
    offset: 54
  });

  // Collapse Navbar
  var navbarCollapse = function() {
    if ($("#mainNav").offset().top > 100) {
      $("#mainNav").addClass("navbar-shrink");
    } else {
      $("#mainNav").removeClass("navbar-shrink");
    }
  };
  // Collapse now if page is not at top
  navbarCollapse();
  // Collapse the navbar when page is scrolled
  $(window).scroll(navbarCollapse);
}); 

Мое приложение / assets / javascripts / credit_card_form.js

$(document).on(function() {
    var show_error, stripeResponseHandler, submitHandler;

        submitHandler = function (event) {
            var $form = $(event.target);
            $form.find("input[type=submit]").prop("disabled", true);

            //If Stripe was initialized correctly this will create a token using the credit card info
            if (Stripe) {
                Stripe.card.createToken($form, stripeResponseHandler);
            } else {
                show_error("Failed to load credit card processing functionality. Please reload this page in your browser.")
            }
            return false;
        };

        $(".cc_form").on('submit', submitHandler);

        stripeResponseHandler = function (status, response) {
            var token, $form;
            $form = $('.cc_form');
            if (response.error) {
                console.log(response.error.message);
                show_error(response.error.message);
                $form.find("input[type=submit]").prop("disabled", false);
            } else {
                token = response.id;
                $form.append($("<input type=\"hidden\" name=\"payment[token]\" />").val(token));
                $("[data-stripe=number]").remove();
                $("[data-stripe=cvc]").remove();
                $("[data-stripe=exp-year]").remove();
                $("[data-stripe=exp-month]").remove();
                $("[data-stripe=label]").remove();
                $form.get(0).submit();
            }
            return false;
        };

        show_error = function (message) {
            if($("#flash-messages").size() < 1) {
                $('div.container.main div:first').prepend("<div id='flash-messages'></div>")
            }
            $("#flash-messages").html('<div class="alert alert-warning"><a class="close" data-dismiss="alert">×</a><div id="flash_alert">' + message + '</div></div>');
            $('.alert').delay(5000).fadeOut(3000);
            return false;
        };

    });

My application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <%= favicon_link_tag asset_path('favicon.png'), :rel => 'icon', :type =>  'image/png' %>
    <%#= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%#= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_link_tag    'application' %>
    <%= javascript_include_tag 'application' %>

    <%= javascript_include_tag "https://js.stripe.com/v2/" %>
  </head>

  <body id="page-top">
    <%#= bootstrap_flash %>
    <% if notice %>
      <div class="alert alert-dismissible alert-success mb-0">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <p><%= notice %></p>
      </div>
    <% end %>
    <% if alert %>
      <div class="alert alert-dismissible alert-danger mb-0">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <%= alert %></p>
      </div>
    <% end %>

    <%= render 'layouts/navbar' %>
    <%= yield %>
    <%= render 'layouts/footer' %>
  </body>
</html>
...