使用jQuery表单验证自定义Ajax请求

Custom Ajax request with jQuery form validation

本文关键字:Ajax 请求 自定义 验证 jQuery 表单 使用      更新时间:2023-09-26

我想用jQuery表单验证插件验证表单,但是我不能用验证处理程序发送自定义Ajax请求:

  $('#headForm').validate(
  {
    //submitHandler: submit,
    errorClass: "invalid",
    rules: {
      title: {maxlength: 50}
    },
    messages: {
      title: {maxlength: 'Max 50 chars'}
    }
  });

我最初的提交处理程序是这样的:

  $('#headForm').submit(function(event) 
  {
    event.preventDefault();
    $.ajax(
      {
        type: "PUT",
        url: "/target",
        data: $('#headForm').serialize(),
        dataType: "json", 
        success: function() 
          { 
            alert("ok");
          }
      });
  });

我试图将其移动到通常的函数并将其注册为验证块中的submitHandler,但它不起作用。

  function submit() { // impossible to pass the event!
    $.ajax( ...
  }

如何将jQuery验证与自定义Ajax请求相结合?

可能的表单验证错误:我删除了验证代码,以查看没有验证代码时提交是否有效。它没有,除非我删除链接到jQuery表单验证库!因此,验证似乎破坏了jQuery的核心。我说过我喜欢动态类型吗?: -)

您是否在submit()函数中定义了参数?

(我猜你没有,这可能就是为什么它不起作用)

我认为你只需要指定'form'参数,然后对该参数调用serialize(),如下所示:

submitHandler: function(form) { 
  $.ajax({
    type: "PUT",
    url: "/target",
    data: form.serialize(),
    dataType: "json", 
    success: function() 
      { 
        alert('ok');
      }
    });
   }

参见文档:http://docs.jquery.com/Plugins/Validation/validate#options