当用户填写预订信息时,他需要以他接收代码的形式验证他的电话号码,并在提交之前将剩余的预订信息放在其中,所以我有下面的视图发送AJAX请求而不提交表格
<%= form_for(@booking) do |f| %>
<%= current_or_not_authenticated_user.email %>
<br>
<%= f.label :patient_id %>
<%= f.collection_select :patient_id, User.order(:created_at), :id, :email %>
<button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#patientModal">
New Patient
</button>
<br>
<div class="form-group">
<%= f.label :type %>
<%= f.select :booking_type, options_for_select([['Physiologist'], ['Psychiatrist'], ['Pediatrician']]) %>
<%= f.hidden_field :customer_id, :value => current_or_not_authenticated_user.id %>
</div>
<div class="form-group">
<%= f.label :address %>
<%= f.collection_select :address_id, Address.where(user_id: current_or_not_authenticated_user.id), :id, :address1 %>
<button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#addressModal">
New Address
</button>
<% if current_user && !current_user[:verified_by_phone_at] %>
<div class="form-group">
<%= label_tag(:phone) %>
<%= text_field_tag(:phone) %>
<button id="smsBtn" type="button" class="btn btn-primary">Send SMS</button>
</div>
<div class="form-group">
<%= label_tag :code %>
<%= text_field_tag :code %>
</div>
<% end %>
<%= f.submit "Confirm Booking" %>
</div>
<br>
<% end %>
<script>
$(document).ready(function() {
$('#smsBtn').on('click', function() {
$.ajax({
url: <%=phone_verification_index_path %>,
type: 'ajax',
data: $('#code').val()
});
});
});
</script>
上点击smsbtn应该去phone_verification控制器,依次调用第三方方法发送短信给用户,然后用户填写自己的密码,并点击提交。
我的问题是,当用户点击smsbtn,@booking表单被提交,我不想表单提交,除非用户点击Confirm Booking,我的jquery工作的唯一方法是当我移动手机领域和smsbtn外部形式。
字段的顺序很重要,因为我不希望用户先找到代码字段,然后再根据它查找手机字段。
如果你想分享一个控制器方法,通常,我把它拉出来成为一个助手,然后让'其他'控制器包含助手。 (在ApplicationController中查看helper()方法) –
@Medo,我认为你的问题的标题不符合实际问题。您只需要在不提交表单的情况下执行AJAX请求。 – Leito
@Leito你是对的,我已经改变了标题,以反映我真正想要的 – Medo