【问题标题】:Send AJAX request without submitting the form发送 AJAX 请求而不提交表单
【发布时间】:2016-10-03 14:35:47
【问题描述】:

用户在填写预订信息时,需要在收到代码的表单中验证他的电话号码,并在提交之前将其与其余预订信息放在一起,所以我有以下观点

<%= 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 表单被提交,我不想提交表单,除非用户单击确认预订,我的 jquery 工作的唯一方法是当我移动两者时电话字段和 smsbtn 外部表单。

字段的顺序很重要,因为我不希望用户先查找代码字段,然后查找其下方的电话字段。

【问题讨论】:

  • 如果你想共享一个控制器方法,通常我会把它拉到一个助手中,然后让“其他”控制器包含这个助手。 (查看 ApplicationController 中的 helper() 方法)
  • @Medo,我认为您的问题标题与实际问题不符。您只是想在不提交表单的情况下执行 AJAX 请求。
  • @Leito 你是对的,我已经更改了标题以反映我真正想要的内容

标签: javascript jquery ruby-on-rails forms


【解决方案1】:

您想阻止 #smsBtn 提交表单,这可以通过不同的方式完成,其中之一是在点击处理程序上调用 event.preventDefault()

$('#smsBtn').on('click', function (event) {
  event.preventDefault()
  // ...
}

【讨论】:

  • 在不了解整个设置的情况下很难说出原因。知道您更清楚自己在寻找什么,您应该能够通过再次搜索找到更好的答案:“防止按钮表单提交表单”。你会发现这个和其他答案可能会有所帮助,甚至可以理解为什么这对你不起作用。祝你好运
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 2021-10-12
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多