Jquery checking success of ajax post

前端 未结 5 1848
庸人自扰
庸人自扰 2020-11-27 15:30

how do i define the success and failure function of an ajax $.post?

5条回答
  •  天命终不由人
    2020-11-27 15:55

    I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

    original Code block:

        post: function( url, data, callback, type ) {
        // shift arguments if data argument was omited
        if ( jQuery.isFunction( data ) ) {
            type = type || callback;
            callback = data;
            data = {};
        }
    
        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });  
    

    Changed Code block:

            post: function (url, data, callback, failcallback, type) {
            if (type === undefined || type === null) {
                if (!jQuery.isFunction(failcallback)) { 
                type=failcallback
            }
            else if (!jQuery.isFunction(callback)) {
                type = callback
            }
            }
            if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
                failcallback = callback;
    
            }
            // shift arguments if data argument was omited
            if (jQuery.isFunction(data)) {
                type = type || callback;
                callback = data;
                data = {};
    
            }
    
    
            return jQuery.ajax({
                type: "POST",
                url: url,
                data: data,
                success: callback,
                error:failcallback,
                dataType: type
            });
        },
    

    This should help the one trying to catch error on $.Post in jquery.

    Updated: Or there is another way to do this is :

       $.post(url,{},function(res){
            //To do write if call is successful
       }).error(function(p1,p2,p3){
                 //To do Write if call is failed
              });
    

提交回复
热议问题