如何在不重定向的情况下提交html表单? [英] How to submit html form without redirection?

查看:142
本文介绍了如何在不重定向的情况下提交html表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 < form action =/ Car / Edit / 17id = myFormmethod =postname =myForm> ...< / form> 

如何在不通过JavaScript / Jquery重定向到另一个视图的情况下提交它?我从StackOverflow中读取了很多答案,但是他们都将我重定向到POST函数返回的视图。

为了实现你想要的,你需要使用 jquery ajax 如下:

  $('#myForm')。submit(function(e){
e.preventDefault();
$ .ajax ({
url:'/ Car / Edit / 17 /',
type:'post',
data:$('#myForm')。serialize(),
成功:function(){
//在表单成功提交后,无论您想要做什么
}
});
});

更新:(根据以下评论)



试试这个:

 函数SubForm(e){
e。的preventDefault();
var url = $(this).closest('form')。attr('action'),
data = $(this).closest('form')。serialize(); $ b $ .ajax({
url:url,
类型:'post',
data:data,
成功:function(){
/ /无论你想在表格成功提交后做什么
}
});
});
}

更新2 这是他的最终解决方案)



这完美无缺。我从 Html.ActionLink(...)

 函数SubForm(){
$ .ajax({
url:'/ Person /Edit/@Model.Id/',
类型:'post',
data:$ ('#myForm')。serialize(),
success:function(){
alert(working);
}
});
}


If I have form like this:

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>

how to submit it without redirecting to another view by JavaScript/Jquery? I read plenty of answers from StackOverflow, but all of them redirect me to the view returned by POST function.

解决方案

in order to achieve what you want, you need to use jquery ajax as below:

$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'/Car/Edit/17/',
        type:'post',
        data:$('#myForm').serialize(),
        success:function(){
            //whatever you wanna do after the form is successfully submitted
        }
    });
});

UPDATED: (based on the comments below)

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 wanna do after the form is successfully submitted
           }
        });
    });
}

UPDATE 2 (the OP added this part as this was his final solution)

This worked flawlessly. I call this function from Html.ActionLink(...)

function SubForm (){
    $.ajax({
        url:'/Person/Edit/@Model.Id/',
        type:'post',
        data:$('#myForm').serialize(),
        success:function(){
            alert("worked");
        }
    });
}

这篇关于如何在不重定向的情况下提交html表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆