2010-04-27 71 views
1

我有一個簡單的表單,我希望以簡單的方式回發到服務器並獲得結果。我在後端使用自定義ISAPI插件,因此使用JSON或其他時髦的東西不是一種選擇。我該如何做到最好?使用jQuery發佈表單值的簡單方法

編輯:我也寧可不使用外部插件,如果可能的話

+1

很遺憾。否則我會爲此提出非常易用的[jQuery表單插件](http://malsup.com/jquery/form/#api)。 – BalusC 2010-04-27 13:48:06

回答

7

使用serialize得到您的格式的字符串表示,然後使用jQuery的post AJAX功能,只需將它張貼。

很簡單的例子(從jQuery的網站使用PHP,但任何URL會做):

$.post("test.php", $("#testform").serialize()); 

如果你有在頁面上多個表單您可以使用按鈕的代碼單擊以獲得正確的形式標識(其中'someButton'可以是任何有效的jQuery選擇器):

$('someButton').click(function() { 
    //old, less efficient code 
    //var formId = $(this).closest("form").attr("id"); 
    //$.post("test.php", $("#" + formId).serialize()); 

    //as per Vincent Robert's suggestion, simplified version 
    $.post("test.php", $(this).closest("form").serialize()); 
}); 
+0

如果我有一個特定表單的提交按鈕,我如何獲得對'serialize()'的表單引用呢? – Chris 2010-04-27 13:57:42

+0

看到我的編輯建議 – 2010-04-27 14:02:56

+2

爲什麼不$(this).closest(「form」)。serialize()? – 2010-04-27 14:10:09

3

Marek評論的另一種方式做同樣的事情。

$.ajax({ 
    type: 'POST', 
    url: YOUR_URL, 
    data: $('#YOURFORM').serialize(), 
    success: function(data) { 
    //Probably should do something that shows it worked. 
    } 
error: function (xhr, ajaxOptions, thrownError){ 
    //Log the error if there was one 
} 

});