简体   繁体   English

回调函数中没有值的变量

[英]Variable without value inside callback function

Im having a strange problem with the following code: 我在以下代码中遇到了一个奇怪的问题:

function getTrxData(trx,inputPar,outputPar,callback) {

var retorno = {};

var URL = '/XMII/Runner?Transaction=' + trx;

var params = "";
for(key in inputPar) 
    params = params + "&" + key + "=" + inputPar[key];

if(!outputPar) 
    outputPar = "*";    

if(params)
    URL = URL + params;

URL = URL + '&OutputParameter=' + outputPar;        

$.ajax({
    type: "GET",
    url: URL,
    async: true,
    success: function(data){
        retorno.datos = $.xml2json(data);
        retorno.tipo    = 'S';          // Success
        retorno.mensaje = "Datos obtenidos correctamente";      
        callback(retorno);
    },
    error: function(jqXHR, textStatus, errorThrown){
        retorno.tipo    = 'E';          // Error
        retorno.mensaje = "Error: " + textStatus;   
        callback(retorno);
    }
});
}

function crearSelect(trx,inputPar,outputPar,selectID,campoTextoXX,campoValor,valorDefault,callback2) {
// At this point campoTextoXX exists and has a value
getTrxData(trx,inputPar,outputPar,function(retorno2) {

            // At this point campoTextoXX is an object equal to callback2

    if(retorno2.tipo == 'E') {
        callback2(retorno2);
        return false;
    }

    var options = "";
    var selected = "";

    $.each(retorno2.datos.Rowset.Row, function(k,v) {
        if(valorDefault == v[campoValor]) {
            selected = " selected='selected'";
        } else {
            selected = "";
        }
        options = options + "<option value='" + v[campoValor] + selected "'>";
        options = options + v[campoTextoXX];    
        options = options + "</option>";
    });

    $("#" + selectID + " > option").remove();
    $("#" + selectID).append(options);

    callback2(retorno2);

});

} }

And the call is like this: 调用是这样的:

crearSelect("Default/pruebas_frarv01/trxTest",{letra:  'V'},"*",'selectID',"CustomerID",'OrderID','',function(retorno) {
alert(retorno.tipo + ": " + retorno.mensaje);
});

The problem is that campoTextoXX and campoValor dont get any value inside the callback function. 问题在于,campoTextoXX和campoValor在回调函数中未获取任何值。 Also, debugging in Chrome shows me that campoTextoXX has the value of the callers callback function: alert(retorno.tipo + ": " + retorno.mensaje); 另外,在Chrome中进行调试显示,campoTextoXX具有调用方回调函数的值:alert(retorno.tipo +“:” + retorno.mensaje);

I dont know what to do next. 我不知道下一步该怎么做。

Any ideas? 有任何想法吗?

Thx 谢谢

The problem appears to be that you are overwriting the variable "pepe" somewhere in your code. 问题似乎是您正在代码中的某个位置覆盖变量“ pepe”。

Also, check how you are assigning your callback function and parameter object. 另外,检查如何分配回调函数和参数对象。 A quick look appears that it is not being supplied the correct parameters. 快速查看,似乎没有提供正确的参数。

You should be careful not to use global variables within your success and error functions. 您应该注意不要在成功函数和错误函数中使用全局变量。 so instead of: 所以代替:

success: function(data){
        retorno.datos = $.xml2json(data);
        retorno.tipo    = 'S';          // Success
        retorno.mensaje = "Datos obtenidos correctamente";      
        callback(retorno);
    }

I think you should do something like: 我认为您应该执行以下操作:

success: function(data){
        var retorno = {};

        retorno.datos = $.xml2json(data);
        retorno.tipo    = 'S';          // Success
        retorno.mensaje = "Datos obtenidos correctamente";      
        callback(retorno);
    }

furthermore you should use Firebug for Firefox to step through your code and watch your variables to ensure that the data is coming in correctly, and not getting overwritten at any point 此外,您应该使用Firefox的Firebug逐步检查代码并查看变量,以确保数据正确输入,并且在任何时候都不会被覆盖

Your control flow is a bit confusing, and another thing you can do is check to make sure your callbacks and variables are correct using some typeof conditionals to make sure they are functions, etc. try doing things like this: 您的控制流程有点混乱,您可以做的另一件事是使用某些类型的条件检查以确保回调和变量正确,以确保它们是函数,等等。尝试执行以下操作:

success: function(data){
            var retorno = {};

            retorno.datos = $.xml2json(data);
            retorno.tipo    = 'S';          // Success
            retorno.mensaje = "Datos obtenidos correctamente";
            if (typeof callback !== "function" || typeof data !== "object"){
                console.log('error');
                throw "callback or data is not correct type";
            }      
            callback(retorno);
        }

and make sure you aren't getting an error in the console. 并确保您在控制台中没有出现错误。

You might find it easier to mange the callback chain by exploiting $.ajax's ability to behave as a jQuery Deferred. 您可能会发现,利用$ .ajax充当jQuery Deferred的功能,可以更轻松地管理回调链。

This allows us very simply to specify the "success" and "error" behaviour in the guise of request.done(...) and request.fail(...) at the point where getTrxData is called rather than inside getTrxData - hence the callback chain is (ostensibly) one level less deep. 这使我们可以非常简单地在调用getTrxData而不是在getTrxData内,以request.done(...)和request.fail(...) 幌子指定“成功”和“错误”行为。回调链(表面上)的深度要低一级。

function getTrxData(trx, inputPar, outputPar) {
    inputPar.Transaction = trx;
    inputPar.OutputParameter = (outputPar || '*');
    return $.ajax({
        url: '/XMII/Runner?' + $.param(inputPar)
    });
}

function makeOptions(obj, selectID, campoTextoXX, campoValor, valorDefault) {
    var $option, selected, $select = $("#" + selectID);
    $("#" + selectID + " > option").remove();
    $.each(obj.datos.Rowset.Row, function(k, v) {
        selected = (valorDefault == v[campoValor]) ? ' selected="selected"' : '';
        $option = $('<option value="' + v[campoValor] + selected + '">' + v[campoTextoXX] + "</option>");
        $select.append($option);
    });
    return obj;
}

function crearSelect(trx, inputPar, outputPar, selectID, campoTextoXX, campoValor, valorDefault, callback) {
    var request = getTrxData(trx, inputPar, outputPar);
    request.done(function(data) {
        var obj = {
            datos: $.xml2json(data),
            tipo: 'S',// Success
            mensaje: "Datos obtenidos correctamente"
        };
        callback(makeOptions(obj, selectID, campoTextoXX, campoValor, valorDefault));
    });
    request.fail(function(jqXHR, textStatus, errorThrown) {
        var obj = {
            tipo: 'E',// Error
            mensaje: "Error: " + textStatus
        };
        callback(obj);
    });
}

crearSelect("Default/pruebas_frarv01/trxTest", {letra:'V'}, "*", 'selectID', "CustomerID", 'OrderID', '', function(retorno) {
    alert(retorno.tipo + ": " + retorno.mensaje);
});

You will see that this is essentially a refactored version of your original code, with significant simplification of the string handling in getTrxData , which appears to work correctly. 您将看到,这实质上是原始代码的重构版本,并且显着简化了getTrxData中的字符串处理,这似乎可以正常工作。

The options code has been pulled out as a separate function, makeOptions , to make the new structure of crearSelect clearer. 该选项的代码已经被拉出作为一个单独的功能, makeOptions ,使新结构crearSelect清晰。 This is not strictly necessary and the code could be re-combined without penalty. 这不是严格必要的,可以重新组合代码而不会造成任何损失。

Tested here insomuch as to make sure it loads and runs through to the "Error" alert, which it does successfully. 在此处进行了大量测试,以确保它可以加载并一直运行到“错误”警报,该警报可以成功执行。 Without access to the server-side script, I can't test/debug the full ajax functionality so you may need to do some debugging. 如果无法访问服务器端脚本,则无法测试/调试完整的ajax功能,因此您可能需要进行一些调试。

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

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