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 实现此功能的帮助,

提前谢谢了

4

8 回答 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();
    });
});
于 2013-01-09T12:53:42.243 回答
4

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

$('#myForm').submit(function(e) {
    e.preventDefault();
    $.post('mail.php', $('#myForm').serialize());
});
于 2013-01-09T12:52:45.370 回答
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();
})
于 2013-01-09T13:12:42.680 回答
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;
    });
});
于 2013-01-09T13:00:30.510 回答
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();
});
于 2017-03-29T08:49:01.187 回答
0

试试这个..

<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();
 })
于 2013-01-09T12:53:14.823 回答
0

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

通过将$("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");
      }
于 2017-03-29T08:45:51.913 回答
-1

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

于 2013-01-09T12:57:10.033 回答