Javascript 如何在没有重定向的情况下提交html表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25983603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:10:24  来源:igfitidea点击:

How to submit html form without redirection?

javascriptjqueryhtmlforms

提问by Duke Nuke

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.

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

采纳答案by Amin Jafari

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

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

$('#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)

更新 2(OP 添加了这部分,因为这是他的最终解决方案)

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");
        }
    });
}

回答by Issa Chanzi

You can achieve that by redirecting form's actionto an invisible <iframe>. It requires no JavaScript or any other type of scripts.

您可以通过将表单重定向action到一个不可见的<iframe>. 它不需要 JavaScript 或任何其他类型的脚本。

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>

<form action="submitscript.php" target="dummyframe">
    <!-- form body here -->
</form>

回答by Steven Black

Place a hidden iFrameat the bottom of your page and targetit in your form:

iFrame在您的页面底部放置一个 hidden并将target其放入您的表单中:

<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

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

Quick and easy. Keep in mind that while the targetattribute is still widely supported (& supported in HTML5) it was deprecated in HTML 4.01. So you really should be using ajax to future-proof.

快捷方便。请记住,虽然该target属性仍然受到广泛支持(在 HTML5 中支持),但它在 HTML 4.01 中已被弃用。所以你真的应该使用 ajax 来适应未来。

回答by Ethuil UI

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:

由于所有当前的答案都使用 jQuery 或 iframe 技巧,因此认为仅使用纯 JavaScript 添加方法没有害处:

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

回答by Anshu Dwibhashi

Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.

好吧,我不会告诉你一个神奇的方法,因为没有。如果您为表单元素设置了 action 属性,它将重定向。

If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"

如果您不希望它重定向,请不要设置任何操作并设置 onsubmit="someFunction();"

In your someFunction()you do whatever you want, (with AJAX or not) and in the ending, you add return false;to tell the browser not to submit the form...

someFunction()你做任何你想做的事情中,(无论是否使用 AJAX),最后,你添加return false;告诉浏览器不要提交表单......

回答by Bojan Petkovski

You need ajax to make it happen. Something like this

你需要 ajax 来实现它。像这样的东西

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact;
        if(name==''||email==''||password==''||contact=='')
        {
            alert("Please Fill All Fields");
        }
        else
        {
            // AJAX Code To Submit Form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

回答by Alexandre Daubricourt

One liner solution as of 2020, if your data is not meant to be sent as multipart/form-dataor application/x-www-form-urlencoded

一种自 2020 年起的班轮解决方案,如果您的数据不打算作为multipart/form-dataapplication/x-www-form-urlencoded

<form onsubmit='return false'>
    <!-- ... -->           
</form>

回答by Nagy Vilmos

See jQuery's postfunction.

参见 jQuery 的post功能。

I would create a button, and set an onClickListener($('#button').on('click', function(){});), and send the data in the function.

我会创建一个按钮,并设置一个onClickListener( $('#button').on('click', function(){});),然后在函数中发送数据。

Also, see the preventDefaultfunction, of jQuery!

另外,请参阅preventDefaultjQuery的功能!

回答by John

The desired effect can also be achieved by moving the submit button outside of the form as described here:

也可以通过将提交按钮移到表单外来实现所需的效果,如下所述:

Prevent page reload and redirect on form submit ajax/jquery

防止页面重新加载和重定向表单提交 ajax/jquery

Like this:

像这样:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

回答by jmojico

Using this snippet you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.

使用此代码段,您可以提交表单并避免重定向。相反,您可以将成功函数作为参数传递并做任何您想做的事情。

function submitForm(form, successFn){
    if (form.getAttribute("id")!='' || form.getAttribute("id")!=null){
        var id = form.getAttribute("id");
    } else {
        console.log("Form id attribute was not set; the form cannot be serialized");
    }

    $.ajax({
        type: form.method,
        url: form.action,
        data: $(id).serializeArray(),
        dataType: "json",
        success: successFn,
        //error: errorFn(data)
    });
}

And then just do :

然后就做:

var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
    console.log("Form submitted");
});