我有一个从用户那里收集信息的表单:我想保留部分信息并将表单与其余信息一起转发到操作中。
我的表格:
<form id="my_form" action="http://place_this_should_submit_after_ajax.com" method="post">
<input type="hidden" name="post_url" id="post_url" value="url_ajax_call_will_post_data_to">
<input type="text" name="name_val" id="name_val">
<input type="text" name="email_val" id="email_val">
<input type="text" name="amount_val" id="amount_val">
<input type="submit" name="submit" value="praying to god">
</form>
我的查询:
$(function() {
$("#my_form").submit( function(e) {
e.preventDefault();
name = $("#name_val").val();
email = $("#email_val").val();
amount = $("#amount_val").val(); // data form.ACTION will need this info
// Validate form field values...
if (validation form field errors) {
// do error stuff...
} else {
// the place I want to send data before posting form to "form.ACTION"
var post_url = $("#post_url").val();
// ALL of the data on the form that my #post_url will scrape and store
var post_data = form.serialize();
// post the form data to the post_url to collect data out of post_data
$.ajax({
type : 'POST',
url : post_url,
data : post_data});
// My pathetic attempt to tell the form to go to form.ACTION
return true;
}
});
}
编辑1:
现在表单发布到 ajax 调用,在那里成功运行页面,但没有将页面发布到 form.ACTION ( http://place_this_should_submit_after_ajax.com )。这是此页面的预期结果。
编辑2:
尽管我已经检查了@Jasen 提交的解决方案,但它并不是一个完整的工作解决方案。但是,它确实解决了 95% 的问题。通过获取不会在 button.CLICK 上提交的表单数据来纠正剩余的问题。
extended from the solution submitted by @Jasen
<form id="my_form" ...>
...
<button class="submit-btn">praying to god</button>
</form>
// Correct way to instantiate a button.CLICK
$(".submit-btn").click(function(e) {
e.preventDefault();
// THIS IS REQUIRED TO GET THE DATA FROM THE FORM GIVEN THE FORM ISN'T SUBMITTED VIA A BUTTON.CLICK
var post_data = $("#my_form").serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data
})
.done(function(result) {
$("#my_form").submit();
});
});