繁体   English   中英

jquery 代码执行发生在其他代码块中

[英]jquery code execution is happening in other code block

我已经制作了这个自定义 ajax function 以避免多次编写 ajax 代码。 我的问题是,如果没有为failcmds变量传递选项 & obj.status"failure" ,那么代码执行也会移至succcmds代码块并执行可用命令。 eg reload(2500)

请帮我找出缺失的部分。

定制 Ajax function

function gr(url, varr, succcmds, failcmds, divid, drestype) {
    $.ajax({
        url: url,
        type: "POST",
        data: varr, 
        beforeSend: function(){
            $('#loadingDiv').show();
        },
        complete: function(){
            $('#loadingDiv').hide();
        },
        success: function(response){
            if(response){
                var obj = $.parseJSON(response);
                if(obj.status == "failure") { 
                    console.log('failcmds : ' + failcmds);
                    if(obj.message) { 
                        gm("e",obj.message); 
                    }
                    if(typeof failcmds === "undefined") {
                        return;
                    }else {
                        $.each(failcmds,function(index, value) {
                            value;
                        });
                    }
                }else if(obj.status == "success"){
                    if(obj.message) { 
                        gm("s",obj.message); 
                    }
                    if(succcmds && succcmds !== null) {             
                        $.each(succcmds,function(ind, val) {
                            val; 
                        });
                    }
                    if (divid && divid !== null){ 
                        if(drestype && drestype == "html"){
                            $("#"+ divid).html(obj.data);
                        }else{
                            $("#"+ divid).append(obj.data); 
                        }
                    }
                }
            }else{
                gm("e", "Invalid Request");
            }
        },
        error: function(){}
    });
}

function的示例使用

$(document).on("click", '.xyz', function() {
    var d = $(this).prop('id');
    var data = 'd='+ $(this).prop('id') + '&typ=sts';
    gm('c','Are you sure you want to do this?');
    $(document).on("click", '#btnYes', function() {
        var sarr = [reload(2500)];
        gr(basepath + "deletereq?", data, sarr);
    });
});

然后代码执行也移动到 succcmds 代码块并执行可用命令

不,它没有。 您甚至在调用 function 之前就执行了这些命令:

var sarr = [reload(2500)];

这将执行reload(2500)并将该执行的结果放入sarr数组中。

相反,将其包装在 function 中:

var sarr = [function () { reload(2500); }];

然后你可以稍后在你喜欢的地方执行 function :

$.each(succcmds,function(ind, val) {
    val(); 
});

基本上,您希望您的“命令”是可执行函数,而不是执行函数的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM