AJAX:在不刷新页面的情况下提交表单

7

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

<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>

我对AJAX还不熟悉,我想要实现的是,当用户点击提交按钮时,我希望mail.php脚本在不刷新页面的情况下在后台运行。

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

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

如果可能的话,我希望能够使用AJAX来实现这个功能。
非常感谢您提前的帮助。

你需要阻止默认操作。尝试在jQuery中使用preventDefault函数。 - Edwin Alex
2
@EdwinAlex 或者只需使用简单的 button,而不是 submit - nanobash
@DaHaKa 我们也可以更改它。但是既然脚本本身已经有选项,为什么我们还需要呢? - Edwin Alex
1
在标记中更改它也有意义 - 提交按钮是专门用来告诉表单它需要提交的。使用按钮代替意味着没有默认行为需要担心停止(e.preventDefault或return false),而且总体上少了JavaScript。 - phatskat
2
更改标记的问题是,您会删除任何禁用JavaScript的人内置的冗余。 - Rory McCrossan
@RoryMcCrossan所说的非常重要。如果您禁用JavaScript并使用“button”而不是“submit”来使用页面,则表单将完全无法工作。 - Juha Untinen
8个回答

10
您需要阻止默认操作(实际提交)。
$(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();
    });
});

+1 感谢您的回复。我想使用 AJAX 来实现这个功能。 - AnchovyLegend
$.post是$.ajax({method: 'POST'})的简写方法。 - Thijs Kramer
1
我的解决方案使用AJAX :-) 它说:“当表单被提交($('form#myForm').on('submit', ...)时,使用AJAX($.post(...))提交数据并阻止默认提交(e.preventDefault())”。 - Kristof Claes
哦... :) 哎呀。我明白你的意思了。唯一的问题是在 mail.php 成功或失败时,HTML 会输出到屏幕上,我希望它能像使用 $.ajax() 一样正常返回,这可能吗? - AnchovyLegend
老实说,这个答案帮了我很多。 - Humphrey

4

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

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

+1 但我认为return false更好(少了一个函数调用和属性访问) - Joseph
@JosephtheDreamer 个人而言,我更喜欢使用 preventDefault(),因为它不会停止事件冒泡等。return false 是一种绝对的大杀器来停止事件。 - Rory McCrossan
+1 感谢您的回复。您能否展示如何使用Ajax完成这个操作? - AnchovyLegend
@MHZ,我不明白你的意思 - 我示例中的代码将解决你的问题,除非你还有其他意思? - Rory McCrossan
ReferenceError: e is not defined - 如果要避免这个错误,e 应该如何定义? - Markus L
显示剩余2条评论

4
/**
 * 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();
})

2

试试这个:

$(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;
    });
});

1
现代的做法(也不需要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();
});

0

如果您使用的是输入类型为提交的,则需要防止默认操作。

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

如果不想使用此默认操作,请使用preventDefault()方法。

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

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

0

试一下这个。。

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

OR

添加

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

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

-1

请查看JQuery Post文档。它应该会对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接