如何从括号中获取变量对象,或者是否有任何方法可以全局声明变量

时间:2014-08-25 05:54:07

标签: javascript sapui5

var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);  
oModel.read('/', null, null, true, function(oData, oResponse)
{
        var dataget = JSON.stringify(oData);        
        var count = oData.results[0].Ort01;
        var Name1 = oData.results[0].Name1;
        var Kunnr = oData.results[0].Kunnr;
        alert(count + "  " +Name1 + "  " +Kunnr);   
});     

这里你看到我可以在括号内找到变量({});如何在括号外得到相同的变量对象...

var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);  
    oModel.read('/', null, null, true, function(oData, oResponse)
    {   
    }); 
var dataget = JSON.stringify(oData);        
var count = oData.results[0].Ort01;
var Name1 = oData.results[0].Name1;
var Kunnr = oData.results[0].Kunnr;
alert(count + "  " +Name1 + "  " +Kunnr); 

有人能帮助我吗?谢谢

3 个答案:

答案 0 :(得分:2)

我不确定你要完成什么,但你声明的函数似乎是回调函数。这意味着它将以异步方式执行,因此您不能简单地在oModel.read行之后添加该代码。

但是,您可以在方法调用之前声明这些变量并在回调方法中使用它们但是您必须意识到您无法知道何时将执行回调函数,因此您无法确定这些变量何时会有任何数据

var count;
var Name1;
var Kunnr;
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);  
oModel.read('/', null, null, true, function(oData, oResponse)
{
    var dataget = JSON.stringify(oData);
    count = oData.results[0].Ort01;
    Name1 = oData.results[0].Name1;
    Kunnr = oData.results[0].Kunnr;
    alert(count + "  " +Name1 + "  " +Kunnr);
});

// Here you can reference to count those variables but you need to make sure
// that callback function is executed already

以上示例显示了如何做到这一点,但无论如何都不是好方法。我认为你应该修改整个执行流程,因为异步执行。我的意思是你应该明白执行流程将继续在回调函数内部而不是在它之外:

var variableDefinedBeforeCallback = .....;
...
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);  
oModel.read('/', null, null, true, function(oData, oResponse)
{
    var dataget = JSON.stringify(oData);
    var count = oData.results[0].Ort01;
    var Name1 = oData.results[0].Name1;
    var Kunnr = oData.results[0].Kunnr;
    alert(count + "  " +Name1 + "  " +Kunnr);

    // If you want to do something with those variables you can call any function
    // here and pass variables defined also before this callback
    anyFunction(variableDefinedBeforeCallback, count, Name1, Kunnr, ...);
});

答案 1 :(得分:0)

var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);

var successCallBack = function(oData,oResponse) {
     var dataget = JSON.stringify(oData);      
     var count = oData.results[0].Ort01;
     var Name1 = oData.results[0].Name1;
     var Kunnr = oData.results[0].Kunnr;
     alert(count + "  " +Name1 + "  " +Kunnr); 
};

oModel.read('/', null, null, true, successCallBack); 

答案 2 :(得分:-1)

只需将read方法中的mParameters.async从true切换为false即可。这会将异步请求更改为同步,它将起作用。