我正在尝试实现 Stripe,他们的文档中列出了以下代码:
<script>
Stripe.setPublishableKey('pk_test_key');
jQuery(function($) {
$('#new_subscription').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('input[type="submit"]').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#new_subscription');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('input[type="submit"]').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
但是我希望能够将其移出 View ,并移至 JavaScript 文件中。正如许多人所知,rails javascript 文件使用 Coffeescript。所以我想知道如何将其转换为可以在 js.coffee 文件中成功运行的东西?
最佳答案
手动执行此操作确实是一个很好的做法,可以更深入地了解coffeescript和js之间的差异。
我通常很懒,只是使用 js2coffee .
可能有一些部分必须在 View 中运行,但这些部分通常非常明显,因为它们依赖于 Rails 服务器知道但 js 文件不知道的键或其他东西有权访问。
关于javascript - 如何将其转换为适合 .js.coffee 的 jQuery 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27911321/