关闭对话框时如何取消待处理的api调用

时间:2019-04-22 21:13:37

标签: javascript jquery reactjs

我必须上传一些文件,因为每个文件api被调用。现在,如果用户要使用对话框中的“取消”按钮取消上传。

请建议如何解决此问题。

我正在使用react和javascript进行文件上传。

文件上传组件位于另一个组件中。

api调用位于utils页面,如图所示

_bulkUpload: function(query, rType,sucessCount,failureCount,name) {
        Api._callAPI(Url.BULK_UPLOAD, 'POST', query, (type, dt) => {
            if(type=="success"){
                let data = dt.res_data;
                    dispatcher.dispatch({
                        type:'DRAFT_BULK_UPLOAD',
                        response: sucessCount,
                        name: name,
                    });
                    dispatcher.dispatch({
                        type:'SNACKBAR',
                        str: dt.res_str,
                        toastType:0,
                    });
                    /*dispatcher.dispatch({
                        type:'DRAFT_BULK_UPLOAD',
                        response: count 
                    });*/
            } else {

                    dispatcher.dispatch({
                        type:'BULK_FAILED',
                        response: failureCount, 
                        name: name
                    }); 
                 dispatcher.dispatch({
                    type: 'SNACKBAR',
                    str: Api._showErrorMsg(dt.status,dt.responseJSON||'')
                });

            }
                dispatcher.dispatch({
                    type: 'LOADER',
                    loader: false
                });
        }, rType);
    },

Api._callAPI函数正在调用一个组件,如图所示。


_callAPI : function(url,method,data,target,cType){
        if(data && data.org_id && ([Url.PRELOGIN_CREATE_SUPER_USER,Url.PRELOGIN_CREATE_USER].indexOf(url) !== -1)){
            // data.org_id = this._getKey('org_id');
        }
        else{
            if([Url.SSO_CHECK,Url.PRELOGIN_FETCH,Url.LOGIN,Url.PRELOGIN_SEND_OTP,Url.PRELOGIN_VERIFY_OTP,Url.PRELOGIN_VERIFY_EMAIL,Url.COUNTRYCODE_TYPEAHEAD].indexOf(url) === -1)
                if(!this._getKey('id') || !this._getKey('value')){
                    return false;
            }
        }

        $.ajax({
            url: BASEURL+url,
            method: method,
            data: data,
            processData: (cType == 'multipart/form-data' ? false :true),
            dataType: (cType == 'multipart/form-data' ? '' :'json'),
            beforeSend: (xhr) => {
                if(this._getKey('id') && this._getKey('value')){
                    xhr.setRequestHeader('XYZ-ID',this._getKey('id'));
                    xhr.setRequestHeader('XYZ-VALUE',this._getKey('value'));
                    if (this._getKey('viewType') == 'Privileged') {
                        xhr.setRequestHeader('XYZ-HASROLE','Y');
                    }
                    else{
                        xhr.setRequestHeader('XYZ-HASROLE','N');
                    }
                    xhr.setRequestHeader('x-csrfvalue',Math.random());
                    if (this._getKey('delegation_bit') === 'true') {
                        xhr.setRequestHeader('XYZ-DELEGATOR', this._getKey('delegator_id'));
                        xhr.setRequestHeader('XYZ-DELEGATION-ID', this._getKey('delegation_id'));
                    }
                }
            },
            contentType: cType ? false : "application/x-www-form-urlencoded",           
            success: (data,textStatus, jqXHR) => {
                if(jqXHR.getResponseHeader('XYZ-ID')){
                    this._setKey('id',jqXHR.getResponseHeader('XYZ-ID'));
                }
                if(jqXHR.getResponseHeader('XYZ-VALUE')){
                    this._setKey('value',jqXHR.getResponseHeader('XYZ-VALUE'));
                }
                /*dispatcher.dispatch({ 
                    type: 'LOADER', 
                    loader: false 
                });*/
                target('success',data);         
            },
            error: (jqXhr,textStatus,error) => {
                dispatcher.dispatch({ 
                    type: 'LOADER', 
                    loader: false 
                });
                if(jqXhr.status == 401){
                    this._clearStorage();
                    // try {
                    //  sessionStorage.setItem('lastVisitedPage', window.location.hash.split("#")[1].split("?")[0]);
                    // }  catch (ex) {
                    //  console.log("Does not support CRUD with Storage");
                    // }
                    this._redirectToLogin();
                } else{
                    target('error',jqXhr,textStatus,error);
                }
            }
        });
    },

文件上传和api调用部分

    _handleFileUpload(){
        let {failedBillCounter,statusArr} = this.state;
        let sucessCount = 0;
        let failureCount = 0;
        var count=failedBillCounter;
        let newFiles = document.getElementById('myFile').files;
        let arr = [];

        if(newFiles.length > 25){
            UserInfoStores.showToast(Errors.MAX_NO_OF_FILE);
            document.getElementById('myFile').value = "";
            return false;
        }
        this.setState({fileCount:newFiles.length})
        document.getElementById('draftBillBar').style.display = 'block';
        //let newData = new FormData();
        for(let i=0;i< newFiles.length;i++){
            let newData = new FormData();
            let files = [];
            let txn_attachments = [];

            if(newFiles[i].size/(1024*1024) > 15){
                count=count+1;
                statusArr.push({name:newFiles[i].name,type:'failed'})
                this.setState({
                    statusArr,
                    failedBillCounter:count,
                    failCounterFlag:true,

                },()=>this.progressBar());

            }
            else{
                newData.append('files-'+i,newFiles[i],newFiles[i].name);
                    txn_attachments.push('files-'+i);
                    newData.append('txn_attachments', txn_attachments);
                    newData.append('source', 'web');

                    newData.txn_attachments = JSON.stringify(txn_attachments);

                    DraftAction.draftBulkUpload(newData,'multipart/form-data', sucessCount,failureCount,newFiles[i].name)

                }
        }
    }

1 个答案:

答案 0 :(得分:0)

您必须创建一个取消上传的函数,为ajaxCall创建一个全局变量

var ajaxCall;

_callAPI : function(...) {
  ... 
  ...
  ajaxCall = $.ajax({ ... });
}

// make a function to call when user click the cancel upload button
_cancelAjaxCall : function() {
  ajaxCall.abort();
}

希望它能起作用...