Ajax提交Form表单

<div class="it610-blog-content-contain" style="font-size: 14px">

After clicking the submit button, FormValidation will submit the form if all the fields are valid.

If you want to do additional tasks instead of submitting the form, you can trigger the success.form.fv event:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            // Some instances you can use are
            var $form = $(e.target),        // The form instance
                fv    = $(e.target).data('formValidation'); // FormValidation instance

            // Do whatever you want here ...
        });
});

Inside the success.form.fv event handler, if you want to submit the form after doing your custom job, just simply use thedefaultSubmit() method:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $(e.target).data('formValidation');

            // Do whatever you want here ...

            // Then submit the form as usual
            fv.defaultSubmit();
        });
});

The next sections demonstrates one of most frequent usage — using Ajax to submit the form.

 

Using Ajax to submit form data

The following code snippet uses the jQuery's serialize() method to get the form data, and then ajax() methods to send the data to the back-end endpoint:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $form.data('formValidation');

            // Use Ajax to submit form data
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: $form.serialize(),
                success: function(result) {
                    // ... Process the result ...
                }
            });
        });
});
 

Using Ajax to submit form data including files

Assume that the form consists of file input:

<input type="file" name="uploadedFiles" multiple />

You can use FormData to collect the form data including selected files:

$(document).ready(function() {
    $(form)
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form    = $(e.target),
                formData = new FormData(),
                params   = $form.serializeArray(),
                files    = $form.find('[name="uploadedFiles"]')[0].files;

            $.each(files, function(i, file) {
                // Prefix the name of uploaded files with "uploadedFiles-"
                // Of course, you can change it to any string
                formData.append('uploadedFiles-' + i, file);
            });

            $.each(params, function(i, val) {
                formData.append(val.name, val.value);
            });

            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(result) {
                    // Process the result ...
                }
            });
        });
});

Please pay attention on contentType and processData options of the jQuery's ajax() method:

  • Setting contentType: false tells jQuery to not add Content-Type to the request
  • Setting processData: false tells jQuery to not convert our data (which is a FormData instance) to a string

On the server side, you can get the uploaded files under the names uploadedFiles-0

uploadedFiles-1, and so forth, depending how many files are chosen.

FormData are supported in modern browsers including IE 10+. You shouldn't use it if your application needs to support previous versions of IE such as IE 8, IE 9.
 

Using jQuery Form plugin

jQuery Form plugin allows us to submit the form, including sending files with an Ajax request easily.

The following snippet shows how to use jQuery Form's ajaxSubmit() method to send all form data, including selected files to the server:

<!-- Including jQuery Form plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/ jquery.form.min.js"></script>

<form id="testForm" method="post" class="form-horizontal">
    ...
</form>
$(document).ready(function() {
    $('#testForm')
        .formValidation({
            ... options ...
        })
        .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target);
            $form.ajaxSubmit({
                // You can change the url option to desired target
                url: $form.attr('action'),
                dataType: 'json',
                success: function(responseText, statusText, xhr, $form) {
                    // Process the response returned by the server ...
                    // console.log(responseText);
                }
            });
        });
});

 

</div>

 

你可能感兴趣的:(JavaScript,jquery)