0

応答が true かどうかを確認するために、5 秒間隔ごとに ajax 呼び出しが行われる次のコード スニペットがあります。受信した応答が true になるまで UI はブロックされ、応答が true になると UI のブロックが解除されます。UI をブロックするために Jquery blockUI v1.0 プラグインを使用しています。

$.fn.suspendResumeonConfirm=function(caseNumber,correlationId){ 
var contents=$('<table style="width:240px;"><tr><td align="center" style="padding: 5px;">Waiting for Response</td></tr><tr><td  align="center" style="padding: 5px;">'+
        '<div id="testProgress"  style="height:10px;background:#f1f1f1;"></div></td></tr><tr><td  align="center" style="padding: 5px;">'+
        '<label class="remainingTime">  </label> Seconds Remaining</td></tr></table>');
        contents.find('div#testProgress').progressbar("destroy").progressbar({value:0}).css("border","1px solid #e4e4e4");
        var progressUpdate=$("<div id='progressUpdate'></div>").append(contents);           
        var timeOut=0,
        response=false;         
        $("body").blockUI(true,{message:progressUpdate,css:{width:250}});
        var interval=setInterval(function() {               
            timeOut++;
            if(timeOut % 5==0){
                var param='entityNumber='+caseNumber+'&correlationId='+correlationId+'&entityType=Case&status=REQ';
                $(this).cAjax('POST','CheckRequestStatus.action',param,false,false,'','Error', true);
                response=strResponseText;
                //$(this).cAjax('POST', 'CheckRequestStatus.action',param,true,true,'serviceCallBack','Error', true,{timeOut:timeOut});
                $('#testProgress').progressbar("option", "value", (timeOut/serviceAlterationTimeout)*100);
                $("div#progressUpdate label.remainingTime").text((serviceAlterationTimeout-timeOut));
            }
            if(timeOut==60){
$('#testProgress').progressbar("option", "value", (timeOut/serviceAlterationTimeout)*100);
                $("div#progressUpdate label.remainingTime").text((serviceAlterationTimeout-timeOut));           
                $("body").blockUI(false);                   
                clearInterval(interval);
 }
        }
        , 1000);
};

$.fn.cAjax =  function(cType, cUrl, cData, cCache, cAsync, cFn, cAlert, cPrData,     functionArguments)
{
var self = $(this).eq(0),
    xhrObj = {};
try{
    strResponseText = "";
    xhrObj = $.ajax({
        type: cType,
        url: cUrl,
        data: cData,
        cache: cCache,
        async: cAsync,
        processData:cPrData? true : false,
        // ; Event will be called on Ajax SUCCESS
        success: function(data, textStatus, XMLHttpRequest) {
            if  ((typeof data).toUpperCase() == "OBJECT"){  
                data = JSON.stringify(data);
            }
                if(data.indexOf('Session Expired') != -1){
                    $(window.location).attr('href',  'Dashboard.action');
                }
                else if(data =="System error")
                {
                    var btnObject = {
                            "OK": function()   {$(this).dialog('close');}};
                      $(this).removeLoadingMsg().cDialog('customErrorDialog',sysErrorObj[0],sysErrorObj[1],false,true,null,null,btnObject,false,null,false,"slide","center");
                }
                else{
                    if(cFn && cFn != '')
                    {
                        if(typeof functionArguments ==   'boolean' || functionArguments)
                            self[cFn](data,   functionArguments);       //calling function by jquery Object notation    
                        else
                            self[cFn](data);
                    }
                    strResponseText = data;
                    return data;
                }
                return false;
    },

        // ; Event will be called on Ajax ERROR
        error:function (xhr, ajaxOptions, thrownError){
                var btnObject = {
                        "OK": function()  {$(this).dialog('close');}},errLabelCon = "";

                errLabelCon = $(this).errorCode(xhr.status);
                errLabelCon = errLabelCon.split(",");
                //abort handling. Callback function will receive   first argment as string "ABORT" and passed arguments if any
                if(ajaxOptions == "abort")
                {
                    if(cFn && cFn != '')
                    {
                        if(typeof functionArguments == 'boolean' || functionArguments)
                            self[cFn]("ABORT", functionArguments);      //calling function by jquery Object notation    
                        else
                            self[cFn]("ABORT");
                    }
                }
                else if(errLabelCon.length == 2)
                // replaced removeLoadingMsg with blockUI so that   current loading should be remove not all
                       $(this).blockUI(false).cDialog(null,errLabelCon[0],errLabelCon[1],false,true,null,null,btnObject,false,null,false,"slide","center");
    },

        // ; Event will be called on Request Complete
        complete:function(XMLHttpRequest,textStatus){
                //; alert("Complete:  "+strResponseText+"  "+textStatus+" "+XMLHttpRequest);
                if(strResponseText.indexOf('Session Expired') != -1){
                    $(window.location).attr('href', 'Dashboard.action');
                }
                if(strResponseText=="System error")
                {
                    var btnObject = {
                            "OK": function(){$(this).dialog('close');}};
                    $(this).removeLoadingMsg().cDialog('customErrorDialog',sysErrorObj[0],sysErrorObj[1],false,true,null,null,btnObject,false,null,false,"slide","center");
                }
    }
    });
    //store the XHR object so that it can be used while ajax in progress
    $(this).data("xhr", xhrObj);
}
catch(e){
    var btnObject = {
            "OK": function(){$(this).dialog('close');},
            "Click to Login": function(){$(this).dialog('close');$(window.location).attr('href', 'LogonFwdAction.action');}};
    var exception = sysErrorObj[1];

    exception += "<br />"+e;

    $(this).cDialog('customErrorDialog',sysErrorObj[0],exception,false,true,null,null,btnObject,false,null,false,"slide","center");
}
};

問題は、setInterval で ajax 呼び出しが行われた後、次の間隔で UI が自動的にブロック解除されることです。しかし、setInterval で ajax 呼び出しを削除すると、blockUI は持続します。

4

1 に答える 1

0

UI のブロックが時期尚早に解除される理由はよくわかりませんが、コードのリファクタリングと整理を行って、結果が理解しやすくなったと思います。

cFn私の主な目的は、合格しなくても済むようにすることでしfunctionArgumentscAjax()jQuery.Deferredこれは、代わりにオブジェクトを渡すことで実現され、cFn機能を で実行できるようになりますsuspendResumeonConfirm()

$.fn.suspendResumeonConfirm = function(caseNumber,correlationId) {
    var contents = $('<table style="width:240px;"><tr><td align="center" style="padding: 5px;">Waiting for Response</td></tr><tr><td align="center" style="padding: 5px;">'+
        '<div id="testProgress" style="height:10px;background:#f1f1f1;"></div></td></tr><tr><td align="center" style="padding: 5px;">' +
        '<label class="remainingTime">  </label> Seconds Remaining</td></tr></table>');
    contents.find('div#testProgress').progressbar("destroy").progressbar({value:0}).css("border", "1px solid #e4e4e4");
    var progressUpdate = $("<div id='progressUpdate'></div>").append(contents);
    var timeOut = 0,
        pollInterval = 5,//seconds
        $$ = {//cache of jQuery objects
            body: $("body"),
            testProgress: $('#testProgress'),
            remainingTime: $("div#progressUpdate label.remainingTime")
        };
    $$.body.blockUI(true, { message:progressUpdate, css:{width:250} });
    function unblockUI() {
        $$.body.blockUI(false);
        clearInterval(interval);
    }
    var param = {'entityNumber':caseNumber, 'correlationId':correlationId, 'entityType':'Case', 'status':'REQ'};
    var interval = setInterval(function() {
        var xhr = $(this).data("xhr");//previous xhr object
        if(xhr) {//if there was a previous iteration
            if(xhr.abort) {
                xhr.abort();//abort
            }
            else if(xhr.reject) {
                xhr.reject();//or reject
            }
        }
        timeOut += pollInterval;
        var def = $.Deferred();
        var xhr = $(this).cAjax('POST', 'CheckRequestStatus.action', param, false, false, true, def);
        $(this).data("xhr", xhr);
        $.when(def).done(function(data) {
            //do other stuff here??
            if(data ...) {//test for a successful response
                unblockUI();
            }
            else {
                $(this).removeLoadingMsg();//??
            }
        }).fail(function(action) {
            switch(action) {
                case "abort":
                    $(this).whatever("ABORT", ...);
                break;
                case 'Session Expired':
                    window.location.href = 'Dashboard.action';
                break;
                case 'System error':
                    $(this).removeLoadingMsg();
                break;
            }
        });
        $$.testProgress.progressbar("option", "value", (timeOut/serviceAlterationTimeout)*100);
        $$.remainingTime.text((serviceAlterationTimeout-timeOut));
    }, pollInterval * 1000);
    setTimeout(unblockUI, serviceAlterationTimeout);//timeout
};

$.fn.cAjax = function(cType, cUrl, cData, cCache, cAsync, cPrData, def) {
    var xhrObj,
        btnObject = {
            "OK": function() {
                $(this).dialog('close');
            }
        };
    try {
        return $.ajax({
            type: cType,
            url: cUrl,
            data: cData,
            cache: cCache,
            async: cAsync,
            processData: cPrData ? true : false,
            success: function(data, textStatus, XMLHttpRequest) {
                if((typeof data).toUpperCase() == "OBJECT") {
                    data = JSON.stringify(data);
                }
                if(data.indexOf('Session Expired') != -1) {
                    def.reject('Session Expired');
                }
                else if(data == "System error") {
                    $(this).cDialog('customErrorDialog', sysErrorObj[0], sysErrorObj[1], false, true, null, null, btnObject, false, null, false, "slide", "center");
                    def.reject('System error');
                }
                else {
                    def.resolve(data);
                }
            },
            error: function (xhr, textStatus, thrownError) {
                var errLabelCon = $(this).errorCode(xhr.status).split(",");
                if(textStatus !== "abort" && errLabelCon.length == 2) {
                    $(this).cDialog(null, errLabelCon[0], errLabelCon[1], false, true, null, null, btnObject, false, null, false, "slide", "center");
                }
                def.reject(textStatus);
            }
        });
    }
    catch(e) {
        var btnObject2 = $.extend(btnObject, {
            "Click to Login": function() {
                $(this).dialog('close');
                $(window.location).attr('href', 'LogonFwdAction.action');
            }
        });
        var exception = sysErrorObj[1] + "<br />" + e;
        $(this).cDialog('customErrorDialog', sysErrorObj[0], exception, false, true, null, null, btnObject2, false, null, false, "slide", "center");
        return $.Deferred().promise();//dummy promise instead of xhr
    }
};

解析エラーがないことを確認するためだけにテスト済み

コードは構造的に堅牢である必要がありますが、いくつかの場所で不完全であるため、最後までやり遂げて、目的どおりに実行する必要があります。

于 2012-08-08T23:24:07.170 に答える