【问题标题】:Easy way to post form values using jQuery使用 jQuery 发布表单值的简单方法
【发布时间】:2010-04-27 13:44:11
【问题描述】:

我有一个简单的表单,我希望以一种简单的方式回发到服务器并获得结果。我在后端使用自定义 ISAPI 插件,因此不能选择使用 JSON 或其他时髦的东西。我怎样才能做到最好?

编辑:如果可能,我也不想使用外部插件

【问题讨论】:

标签: jquery forms post


【解决方案1】:

使用serialize 获取表单的字符串表示形式,然后使用jQuery 的post AJAX 函数简单地发布它。

非常简单的示例(来自使用 PHP 的 jQuery 网站,但任何 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());
});

【讨论】:

  • 如果我有一个特定表单的提交按钮,我如何获得serialize()它的表单引用?
  • 为什么不 $(this).closest("form").serialize() ?
【解决方案2】:

与 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
 }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2019-02-19
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多