Javascript布尔结果失败

时间:2016-11-02 10:01:52

标签: javascript jquery

为什么这个变量(lanFound)变得未定义?

我得到以下输出:

灯泡时刻! :)

当我输入输出序列时就把它拿走了! ajax是asynch,所以在代码继续之后真实回来了!无论如何,我会发帖,对某人来说可能很方便!

  • 测试:DK
  • 结果是:undefined
  • / sites / cspdKnowledgeAssemblyPlatform / ApprovedContent / DKCover Letter.docx成功

我有一组docx文件,但是我正在添加对语言的支持,但为了测试文件(docx)已添加,我使用以下代码(确定这是一个很长的变体,允许我调试):< / p>

    fileUrl = filePath + fileName;
        if (lan != "EN"){
            showNotification("testing for: " + lan);
            var lanFound = false;
                lanFound = checkURL(filePath + lan + fileName);
                showNotification("result is: " + lanFound);
            if(lanFound){
                debugger;
                fileUrl = filePath + lan + fileName;
                showNotification("found " + fileUrl); 
            }
        }

        function checkURL(urlFileName){
            $.get(urlFileName)
            .fail(function() {
                showNotification(urlFileName + " failed");
                return false;
            })
            .done (function() {
                 showNotification(urlFileName + " succeeded");
                return true;
            });
        }

你可以忽略这一点 - 只是添加了&#34; showNotification&#34;)

的上下文
        function showNotification(content){
             var currentText =  $( "#resultpanel" ).html();
             currentText = currentText + "<br/>" + content;
             $( "#resultpanel" ).html(currentText);  
        }

1 个答案:

答案 0 :(得分:1)

你不能以这种方式调用ajax调用,代码将在返回结果之前传递,因为它是异步的,结果是变量在代码传递它时被读取为未定义。 / p>

很抱歉,当我输入问题时,我意识到答案,但无论如何都要发布,因为这对某人来说可能很方便。