为什么这个变量(lanFound)变得未定义?
我得到以下输出:
灯泡时刻! :)
当我输入时,输出的顺序就暴露了! ajax 是异步的,所以 true 会在代码继续后返回!无论如何我都会发帖,可能对某人有用!
- 测试:DK
- 结果是:未定义
- /sites/cspdKnowledgeAssemblyPlatform/ApprovedContent/DKCover Letter.docx 成功
我有一组 docx 文件,但正在添加对语言的支持,但为了测试已添加的文件(docx),我使用以下代码(好吧,这是一个很长的变体,允许我调试):
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;
});
}
您可以忽略它 - 刚刚为“showNotification”上下文添加)
function showNotification(content){
var currentText = $( "#resultpanel" ).html();
currentText = currentText + "<br/>" + content;
$( "#resultpanel" ).html(currentText);
}
最佳答案
您不能以这种方式调用 ajax 调用,代码将在返回结果之前传递,由于它是异步的,结果是变量,在代码传递它的点处被读取为未定义。
抱歉,当我输入问题时,我意识到了答案,但还是发布了,因为这可能对某人有用。
关于Javascript bool 结果失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40377083/