form submission converted to ajax request

formSubmitToAjax resource link: formSubmitToAjax.js

github link: https://github.com/1499610503/formSubmitToAjax

Download the file above or copy the code below

formSubmitToAjaxl.js:

$(function() {
    
    
    $('form').on('submit', function(event) {
    
    
        var that = this;
        event.preventDefault()
        console.log(this)
        var url = this.action || ''
        var type = this.method || 'post'
        var formdata = new FormData(this)
        console.log({
    
    
            url,
            type,
        })
        $.ajax({
    
    
            url: url,
            type: type,
            data: formdata,
            processData: false,
            success: function(res) {
    
    
                if (that.success) {
    
    
                    that.success(res)
                    return
                }
                console.log('提交成功', res)
                alert('提交成功')
            },
            error: function(err) {
    
    
                if (that.error) {
    
    
                    that.error(err)
                    return
                }
                console.log('提交失败', err)
                alert('提交失败')
            }
        });
    })
})

After introducing formSubmitToAjaxl.js, all form submissions on the page will be submitted in ajax form.

You can set the success (request success) and error (request failure) processing methods for the specified form:
the return data should be in json format

$('#form1').get(0).success=function(res){
    
    
console.log(res)
}
$('#form1').get(0).error=function(err){
    
    
console.log(err)
}

I used jq in formSubmitToAjaxl.js, so I need to import the jq file before introducing formSubmitToAjaxl.js

The code size of formSubmitToAjaxl.js is small and simple. It actually prevents the default submit behavior of the form, then sends the form data to the target URL in the form of ajax, and finally calls the success or error method based on success or failure.

Guess you like

Origin blog.csdn.net/weixin_44646763/article/details/125926539