2013-01-09 189 views
5

我有类似以下形式:AJAX:提交一个表单而无需刷新页面

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

提前感谢

+0

您需要防止默认操作。尝试在jQuery中防止默认功能 –

+2

@EdwinAlex或者只是使用简单的'button'而不是'submit' – tnanoba

+0

@DaHaKa我们也可以改变它。但为什么我们需要在脚本本身有选项。 –

回答

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

+1感谢您的答复,我想做到这一点使用AJAX – AnchovyLegend

+0

$。员额为$阿贾克斯(的速记方法。 (方法:'POST'}); –

+1

我的解决方案*是*使用AJAX :-)它说:“当提交表单('$''form#myForm')。on('submit',...') ,使用AJAX('.post(...)')发布数据并阻止默认提交('e.preventDefault()')“。 –

4

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

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

+1但我认为'返回FALSE'会更好(少了一个函数调用和属性访问) – Joseph

+0

@JosephtheDreamer我个人更喜欢'的preventDefault()',因为它没有阻止事件冒泡等'回报FALSE'是一个绝对的蠢事的方法来阻止一个事件。 –

+0

+1感谢您的回复。您能否展示如何在Ajax中完成这项工作? – AnchovyLegend

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

您需要防止默认操作,如果您使用的输入类型为提交<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"); 
     } 
0

现代的方式来做到这一点(这也不需要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(); 
});