Javascript AJAX:提交表单而不刷新页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14235596/
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-24 16:07:05  来源:igfitidea点击:

AJAX: Submitting a form without refreshing the page

javascriptjqueryajax

提问by AnchovyLegend

I have a form similar to the following:

我有一个类似于以下的表格:

<form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.phpscript to run behind the scenes without refreshing the page.

我是 AJAX 的新手,我想要完成的是当用户单击提交按钮时,我希望mail.php脚本在不刷新页面的情况下在幕后运行。

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

我尝试了类似下面的代码,但是,它似乎仍然像以前一样提交表单而不是我需要它(在幕后):

$.post('mail.php', $('#myForm').serialize());

If possible, I would like to get help implementing this using AJAX,

如果可能,我想获得帮助,使用 AJAX 实现这一点,

Many thanks in advance

提前谢谢了

回答by Kristof Claes

You need to prevent the default action (the actual submit).

您需要阻止默认操作(实际提交)。

$(function() {
    $('form#myForm').on('submit', function(e) {
        $.post('mail.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});

回答by Rory McCrossan

You haven't provided your full code, but it sounds like the problem is because you are performing the $.post()on submit of the form, but not stopping the default behaviour. Try this:

您还没有提供完整的代码,但听起来问题是因为您正在执行$.post()表单的提交,但没有停止默认行为。尝试这个:

$('#myForm').submit(function(e) {
    e.preventDefault();
    $.post('mail.php', $('#myForm').serialize());
});

回答by Bodybag

/**
 * it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
 * for explanation why, try googling event delegation.
 */

//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
    /*
     * do ajax logic  -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
     * $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
     * i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
     */
    //example using post method
    $.post('mail.php', $("#myForm").serialize(), function(response){
        alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
    })
    //example using ajax method
    $.ajax({
        url:'mail.php',
        type:'POST',
        data: $("#myForm").serialize(),
        dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
        success: function(response){
            alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
        },
        error: function(response){
            //as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
            alert("something went wrong");
        }
    })
    //preventing the default behavior when the form is submit by
    return false;
    //or
    event.preventDefault();
})

回答by Japneet Singh

try this:

尝试这个:

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});

回答by SANJAY ARAKERI

You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.

如果您使用输入类型作为 submit ,则需要防止默认操作<input type="submit" name="submit" value="Submit">

By putting $("form").submit(...)you're attaching the submit handler, this will submit form (this is default action).

通过放置$("form").submit(...)您附加提交处理程序,这将提交表单(这是默认操作)。

If don't want this default action use preventDefault()method.

如果不希望此默认操作使用preventDefault()方法。

If you are using other than submit, no need to prevent default.

如果您使用的不是提交,则无需防止默认。

 $("form").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'save.asmx/saveData',
      dataType: 'json',
      contentType:"application/json;charset=utf-8",
      data: $('form').serialize(),
      async:false,
      success: function() {
        alert("success");
      }
      error: function(request,error) {
        console.log("error");
      }

回答by Greg

The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfillif that's an issue. For example:

执行此操作的现代方法(也不需要 jquery)是使用fetch API。较旧的浏览器不支持它,但如果这是一个问题,则有一个polyfill。例如:

var form = document.getElementById('myForm');
var params = {
  method: 'post',
  body: new FormData(form),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
};

form.addEventListener('submit', function (e) {
  window.fetch('mail.php', params).then(function (response) {
    console.log(response.text());
  });
  e.preventDefault();
});

回答by bipen

try this..

尝试这个..

<form method="post" action="mail.php" id="myForm" onsubmit="return false;">

OR

或者

add

添加

e.preventDefault();in your clickfunction

e.preventDefault();在你的click函数中

 $(#yourselector).click(function(e){
      $.post('mail.php', $(this).serialize());
      e.preventDefault();
 })

回答by a blue marker

Take a look at the JQuery Postdocumentation. It should help you out.

查看JQuery Post文档。它应该可以帮助你。