2013-01-09 161 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(); 
});