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

IT技术 javascript jquery ajax
2021-03-01 06:26:37

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

<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 实现这一点,

提前谢谢了

6个回答

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

$(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 来完成这个。
2021-05-02 06:26:37
我的解决方案使用 AJAX :-) 它说“提交表单 ( $('form#myForm').on('submit', ...) 时,使用 AJAX ( $.post(...))发布数据并防止默认提交 ( e.preventDefault())”。
2021-05-12 06:26:37
哦... :) oop。我明白你在说什么。唯一的问题是成功或失败或mail.phphtml 输出到屏幕上,我希望返回,因为它通常会使用 $.ajax(),这可能吗?
2021-05-12 06:26:37
老实说,这个答案对我有帮助
2021-05-20 06:26:37
$.post 是 $.ajax({method: 'POST'}); 的简写方法;
2021-05-21 06:26:37

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

$('#myForm').submit(function(e) {
    e.preventDefault();
    $.post('mail.php', $('#myForm').serialize());
});
唯一的问题是成功或失败或将 mail.php html 输出到屏幕上,我希望将其返回,因为它通常会使用 $.ajax(),这可能吗?就像是success: function(data){ $(".smart").html(data); ...
2021-04-26 06:26:37
+1 感谢您的回复。你能展示一下如何在 Ajax 中做到这一点吗?
2021-04-27 06:26:37
+1 但我认为 areturn false会更好(少一个函数调用和属性访问)
2021-05-03 06:26:37
@MHZ我不明白你的意思——我的例子中的代码会解决你的问题,除非你还有别的意思?
2021-05-09 06:26:37
@JosephtheDreamer 我个人更喜欢preventDefault()它,因为它不会停止事件冒泡等。这return false停止事件的绝对错误方法。
2021-05-12 06:26:37
/**
 * 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();
})

试试这个:

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

执行此操作的现代方法(也不需要 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();
});