在表单验证器中调用$ .ajax

时间:2017-11-02 13:26:42

标签: jquery ajax jquery-validate

如何在jQuery验证$.ajax()中编写submitHandler()调用?以下是我的代码。我只有一个Empname的文字。

$('#FormSubmit').validate({
  rules: {
    EmpName: {
      required: true,
      minlength: 5,
      maxlength: 10
    },
    meassages: {
      EmpName: {
        required: function() {
          return $('#lblName').text('Name Req min2 max15');
        }
        submitHandler: function(FormSubmit) {
          $.ajax({
            url: "http://localhost:10948/Api/Home/PostData",
            method: "POST",
            contentType: 'application/x-www-form-urlencoded',
            success: function() {

            }
          })
        },
<form id="FormSubmit" method="post">
  <div class="form-horizontal">
    <div class="form-group">
      <b>EmpName</b><input type="text" name="EmpName" required />
      <span id="lblName"></span>
    </div>
  </div>
  <input type="submit" value="Submit" />
</form>

它没有处理我的url,也没有给我一个错误:

  

HTTP错误405.0 - 不允许的方法

1 个答案:

答案 0 :(得分:4)

首先请注意,您有几个语法问题,例如未正确关闭对象,messages输入错误,required消息需要返回字符串值。

其次,submitHandler只是表单有效时执行的函数。您需要将实际的$.ajax逻辑放在其中,而不仅仅是请求参数:

$('#FormSubmit').validate({
  rules: {
    EmpName: {
      required: true,
      minlength: 5,
      maxlength: 10
    }
  },
  messages: {
    EmpName: {
      required: 'Name Req min2 max15'
    }
  },
  submitHandler: function(form) {
    $.ajax({
      url: "http://localhost:10948/Api/Home/PostData",
      method: "POST",
      data: $(form).serialize(),
      success: function(response) {
        console.log('it worked!');
        console.log(response);
      }
    });
  }
});