我的函数的值是未定义的 [英] The value of my function is undefined

查看:112
本文介绍了我的函数的值是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能,它将翻译字符串和短语为其他功能,并应该返回一个数组与翻译的部分。
当我尝试在另一个函数中调用函数并捕获返回的值时,我不断接收到返回值未定义的消息。当我不让翻译功能返回一个值,但让她做出警告与她应该返回的价值..一切顺利。



所以他们是我做的事情,阻止函数translate()正确返回值,或者使函数picklanguage()没有收到返回的值。 >

  function translate(translateObject)
{
var translations = new Array();

dojo.xhrPost({
url:'http://'+window.location.hostname+'/translate/translate',
content:{str:dojo.toJson (translateObject)},
handleAs:json,
timeout:2000,
load:function(response){

dojo.forEach(response.items, function(strg){
var key = strg.string;
translations [strg.string] = strg.translation;
});

return translations;
},
错误:function(response){
return'Ben';
}
});
}

函数pickLanguage()
{
var language = translate({title:'Kies hier je gewenste taal',dutch:'Nederlands',french: '法语',德语:'Deutch',英文:'English'});

errorDialog = new dijit.Dialog({
content:dump(language),
style:width:450px
});

errorDialog.show();
}


解决方案

您正在使用 A JAX– 异步呼叫。



加载回调在之后运行一段时间,您的功能完成;您不能从中返回值。



您需要使用回调函数返回值,方式 xhrPost


I have this function wich will translate strings and phrases for other functions and should return an array with the translated parts. When I try to call the function in another function and captcher the returned value, I keep recieving the message that the returned value is undefined. When I don't let the translate function return a value but make her do an alert with the value she should return .. everything goes well.

So their is something I do what prevents the function translate() to return the value properly or what makes the function picklanguage() not recieve the returned value.

function translate(translateObject)
{
    var translations = new Array();

    dojo.xhrPost({
        url: 'http://'+window.location.hostname+'/translate/translate',
        content: { str: dojo.toJson(translateObject) },
        handleAs: "json",
        timeout: 2000,
        load: function(response){

            dojo.forEach(response.items, function(strg){
                  var key = strg.string;
                  translations[strg.string] = strg.translation;
                });

            return translations;
        },
        error: function(response){
                return 'Ben';
        }
    });
}

function pickLanguage()
{
    var language = translate({title: 'Kies hier je gewenste taal', dutch: 'Nederlands', french: 'French', german: 'Deutch', english: 'English'});

    errorDialog = new dijit.Dialog({
          content: dump(language),
          style: "width: 450px"
      });

    errorDialog.show();
}

解决方案

You're using AJAX – asynchronous calls.

The load callback runs some time after your function finishes; you cannot return a value from it.

You need to return the value using a callback, the way xhrPost does.

这篇关于我的函数的值是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆