题意:“如何在不重定向的情况下提交HTML表单”
问题背景:
If I have a form like this,
“如果我有一个这样的表单,”
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>
how can I submit it without redirecting to another view by JavaScript/jQuery?
“我该如何通过JavaScript/jQuery提交它,而不重定向到另一个视图?”
I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.
“我在Stack Overflow上读了很多回答,但它们都将我重定向到POST函数返回的视图。”
问题解决:
In order to achieve what you want, you need to use jQuery Ajax as below:
“为了实现你想要的,你需要使用如下的jQuery Ajax:”
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: '/Car/Edit/17/',
type: 'post',
data:$('#myForm').serialize(),
success:function(){
// Whatever you want to do after the form is successfully submitted
}
});
});
Also try this one:
也可以尝试以下方式:
function SubForm(e){
e.preventDefault();
var url = $(this).closest('form').attr('action'),
data = $(this).closest('form').serialize();
$.ajax({
url: url,
type: 'post',
data: data,
success: function(){
// Whatever you want to do after the form is successfully submitted
}
});
}
Final solution 最终解决方案
This worked flawlessly. I call this function from Html.ActionLink(...)
“这工作得非常顺利。我是通过 `Html.ActionLink(...)` 调用这个函数的。”
function SubForm (){
$.ajax({
url: '/Person/Edit/@Model.Id/',
type: 'post',
data: $('#myForm').serialize(),
success: function(){
alert("worked");
}
});
}