我希望通过 jQuery/AJAX 在 Rails 上提交表单。我的表单不会在第一次点击时提交,而是在第二次点击时提交。我希望以这种方式运行 rails,因为我被告知我可以从服务器获得响应,让我知道事情已经成功。你能帮忙的话,我会很高兴。
表单验证.js
$(document).ready(function () {
$('#sms_form').validate({
rules: {
phone_number: {
required: true,
digits: true,
phoneUS: true,
maxlength:10
},
text_message: {
required: true,
maxlength: 160
},
messages: {
phone_number: {
required: "Enter a valid phone number",
minlength: jQuery.format("Enter at least {10} characters"),
remote: jQuery.format("{0} is not a number")
},
text_message: {
required: "text message cannot be blank"
}
}
},
submitHandler: function (form) {
$('#sms_form').submit(function() {
$.ajax({
type: 'POST',
url: 'branch#call_sms',
complete: function() {
$("#sms_status").append('<h3>Status: SENT</h3> </br>');
$("#sms_status").append('<a href="#" id="sms_back_button" class="sms_button">back</a>');
$("#sms_status").slideFadeToggle();
$("#sms_form_box").slideFadeToggle();
$('#sms_form').ajaxSubmit();
},
success: function() {
// some code?
}
})
return false; // prevents normal behaviour
});
}
});
});
这是表格*
<%= template_start -%>
<%-
@text_message = "message"
%>
<a href="#" id="text-message" class="sms_button">sms text system</a>
<div class="sms pop">
<div class="close"></div>
<%= form_for :call_sms, url: {action: "call_sms"},
:method => :post, :remote => true, :html => {:id => 'sms_form'} do |f| %>
<div id='sms_form_box'>
<p>
<%= f.label 'phone_number', 'phone number' %>
<%= text_field_tag :phone_number %>
</p>
<p>
<%= f.label 'message', 'text message' %>
<%= text_area_tag :text_message, @text_message, :size => '36x8' %>
</p>
<p>
<%= f.submit "send text message", :id =>'send_sms' %>
</p>
</div>
<div id='sms_status'></div>
<% end %>
</div>
<%= template_end -%>
这是控制器方法
def call_sms
@text_number = params[:phone_number]
@text_message = params[:text_message].to_s
@sms = ShortMessagingService.new
@sms.send(@text_number, @text_message)
@sms_message = @sms.sent?
respond_to do |format|
format.js if request.xhr?
format.html { render :nothing => true}
end
end