【问题标题】:AJAX: Submitting a form without refreshing the pageAJAX:提交表单而不刷新页面
【发布时间】:2013-01-09 12:50:16
【问题描述】:

我有一个类似下面的表格:

<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 中的默认功能
  • @EdwinAlex 或者只使用简单的button 而不是submit
  • @DaHaKa 我们也可以更改它。但是为什么我们需要在脚本本身有选项时需要。
  • 在标记中更改它也很有意义 - 提交按钮专门用于告诉表单它需要提交。使用按钮代替意味着无需担心停止的默认行为(例如,preventDefault 或 return false),并且总体而言,更少的 Javascript。
  • 更改标记的问题是您删除了禁用 javascript 的任何人的内置冗余。

标签: javascript jquery ajax


【解决方案1】:

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

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

您尚未提供完整代码,但听起来问题是因为您在提交表单时执行了$.post(),但并未停止默认行为。试试这个:

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

【讨论】:

  • +1 但我认为return false 会更好(少一个函数调用和属性访问)
  • @JosephtheDreamer 个人我更喜欢 preventDefault(),因为它不会阻止事件冒泡等。return false 是一种绝对愚蠢的停止事件的方法。
  • +1 感谢您的回复。能否请您说明如何在 Ajax 中完成此操作?
  • @MHZ 我不明白你的意思——我的例子中的代码会解决你的问题,除非你还有什么意思?
  • 唯一的问题是成功或失败或者mail.php html被输出到屏幕上,我希望返回它,因为它通常会使用$.ajax(),这可能吗?类似success: function(data){ $(".smart").html(data); ...
【解决方案3】:
/**
 * 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();
})

【讨论】:

    【解决方案4】:

    试试这个:

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

    【讨论】:

      【解决方案5】:

      执行此操作的现代方法(也不需要 jquery)是使用 fetch API。较旧的浏览器won't support it,但如果这是一个问题,有一个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();
      });
      

      【讨论】:

        【解决方案6】:

        试试这个..

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

        添加

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

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

        【讨论】:

          【解决方案7】:

          如果您使用输入类型作为提交&lt;input type="submit" name="submit" value="Submit"&gt;,则需要阻止默认操作。

          通过输入$("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");
                }
          

          【讨论】:

            【解决方案8】:

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

            【讨论】:

              猜你喜欢
              • 2017-03-17
              • 2017-04-09
              • 2013-07-10
              • 2014-03-03
              • 1970-01-01
              • 2020-10-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多