我有一个Stripe表单,尝试使用Ajax提交时我一直遇到错误。
下面是完整的代码,但是我一直试图调整的行是form_tag
行。与此:
<%= form_tag(buy_path(@product.id), id:'payment-form', authenticity_token: true, remote: true) do %>
我收到此错误:
ActionController::UnknownFormat in UsersController#buy
ActionController::UnknownFormat
respond_to do |format| <= HIGHLIGHTED
format.js
end
但是当我指定js
格式时:
<%= form_tag(buy_path(@product.id, format: :js), id:'payment-form', authenticity_token: true, remote: true) do %>
js文件只是呈现为纯html。与之类似,浏览器只打印内容:
$("html").hide();
这是我的完整代码。当我删除嵌入式javascript时,buy.js.erb
会正常显示,因此javascript中添加了一些东西,使浏览器无法将请求作为ajax处理。
buy.html.erb
<!-- The form. Fields are inserted into #card-element with JS -->
<%= form_tag(buy_path(@product.id), id:'payment-form', authenticity_token: true, remote: true) do %>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<button id="submit-card">Submit Payment</button>
<div id="cancel-bid">Cancel</div>
<% end %>
<script type="text/javascript">
var stripe = Stripe('<%= key %>');
var elements = stripe.elements();
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Create a token or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the customer that there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
users_controller / rb
def buy
respond_to do |format|
format.js
end
end
buy.js.erb
$("html").hide();