0
$(function () {
  $('#submit').submit(function() {

    var isValid = document.getElementById("form-setting").checkValidity();

    var data = {};
    data.id = $("#id").val();
    data.title = $("#title").val();
    data.content = $("#content").val();
    data.author = $("#author").val();
    data.email = $("#email").val();

    if (isValid) {

    $.ajax({
      type: 'POST',
      data: JSON.stringify(data),
      contentType: 'application/json',
      url: '/admin/setting',
      success: function (data) {
        console.log('success');
        console.log(JSON.stringify(data));
      }
    });
    }
  });
});

So I have the above code where I will get all the value of the field that filled by the user, and only send the object to the node.js server if everything is filled and validated.

The problem here is that if I have that isValid check there is nothing being sent to the server at all.

In fact there is no action happens inside that if statement at all because I tried put some alert in there and nothing is showing at all.

4

2 回答 2

1

尝试防止表单提交处理程序的默认行为:

$(function () {
    $('#submit').submit(function (e) {

        var isValid = document.getElementById("form-setting").checkValidity();
        alert(isValid); //<<< ALERT HERE
        var data = {};
        data.id = $("#id").val();
        data.title = $("#title").val();
        data.content = $("#content").val();
        data.author = $("#author").val();
        data.email = $("#email").val();

        if (isValid) {
            alert('PASS'); //<<< ALERT HERE
            $.ajax({
                context: this, //use for success callback
                type: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json',
                url: '/admin/setting',
                success: function (data) {
                    console.log('success');
                    console.log(JSON.stringify(data));
                    //this.submit();  //uncomment this line if you want to submit form
                }
            });
        }
        e.preventDefault();
    });

});

于 2013-06-30T13:10:46.767 回答
0
if (isValid) {
  // send your ajax call
  return false; // plus don't want your form being submited since you allready submited it through ajax 
}
else{
  return false; // since you want to prevent the submission
}

但更好的选择是根本不使用表单,并在一个简单的按钮上添加一个监听器

于 2013-06-30T13:13:46.700 回答