使用jQuery发布表单值的简便方法
我有一个简单的表单,我希望以简单的方式回发到服务器并获得结果。 我在后端使用自定义ISAPI插件,因此使用JSON或其他时髦的东西不是一种选择。 我怎么能做到最好?
编辑:如果可能的话,我也不想使用外部插件
使用serialize
来获取表单的字符串表示,然后使用jQuery的post
AJAX函数发布它。
非常简单的例子(来自jQuery的网站使用PHP,但任何URL都可以):
$.post("test.php", $("#testform").serialize());
如果页面上有多个表单,则可以在单击按钮时使用此代码以获取正确的表单ID(其中’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()); });
与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 } });