Ajax文件检查成功后不改变变量
Ajax filecheck not changing variables upon success
我使用ajax来检查我的图像目录中是否有可用的文件。如果它在那里,我将它附加到我的html代码中,并将布尔值更改为true,让用户知道找到了它。如果没有找到文件名,我检查它是否是一个由2部分组成的图像(在图像名称的末尾连接数字1和2并生成2个图像)。布尔值也被更改为true,表示找到了图像。尽管如果没有单个或两个部分的图像,代码应该只是在ajax中出错,将布尔值保留为false,告诉用户没有图像。
我的逻辑在所有事情上都工作得很好,除了在没有图像时通知用户。在ajax成功函数中,图像总是追加(无论是成功还是错误),但是布尔值在成功后永远不会改变。这是我正在运行的代码。
boolean = false //declared globally
function tableSelect(location){
$("#popupPhoto").text("");
var part = $("#table"+location).text().split(" ");
//part[0] always empty
for(var i=1;i<part.length;i++){
//change default value to false
boolean = false;
/* original code
imageExists(part[i]);
//when no file... is found, boolean stays false, causing this if statement to function
if(boolean == false){
alert("No Information for "+imagename+" of "+part[i]);
//displayes image that says "No Information Available"
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/nia.png', "class": 'popphoto', alt: 'NIA' }));
}
*/
//new code
imageExists(part[i]).fail(function () {
alert("No Information for "+imagename+" of "+part[i]);
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/nia.png', "class": 'popphoto', alt: 'NIA' }));
})
}//Displays images in popup
$("#popupPhoto").addClass("ui-popup-active");}
下面是检查图像
的函数function imageExists(part){
var url = "images/imagedir/"+part+".png";
$.ajax({
url:url,
type:'HEAD',
error: function()
{
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'1.png', "class": 'popphoto', alt: part.concat("1") }));
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'2.png', "class": 'popphoto', alt: part.concat("2") }));
//boolean = true;
//boolean changes here
},success: function()
{//boolean will not change here
//boolean = true;
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'.png', "class": 'popphoto', alt: part }));
}
});
}
我知道这可能是我不理解这个函数的细节和它是如何工作的,但如果有人能帮助解决这个问题或建议一个更好的方法来做到这一点,这基本上是我正在寻找的。
为什么AJAX被称为异步?
调用imageExists
后的代码在ajax调用触发后立即运行。它不会等待ajax调用返回。
你有两个选项来解决这个问题;使用成功/错误回调或使用承诺。在这两种情况下,都不需要全局布尔值,应该删除该变量。
回调:function imageExists(part){
...
$.ajax({
...
error: function () {
// move the boolean == false code in to the error handler
},
success: function() {
// move the boolean == true code in to the success handler
}
});
}
承诺:
imageExists(part[i]).then(function () {
// move the boolean == true code in to the then handler
}).fail(function () {
// move the boolean == false code in to the failhandler
}
相关文章:
- IF 语句不改变变量的结果
- 为什么不是'这个CanvasJS脚本动态地改变变量
- 在php中改变变量,但在javascript中相同的变量不变
- 为什么Javascript不使用onChange来改变变量?
- 添加一个DOM/SVG元素与d3 javascript库改变变量引用/范围,为什么
- 通过点击按钮改变变量的值
- 在按下键后改变变量
- JQuery改变变量/成本后点击
- Eventlistener点击不改变变量时按下
- 改变变量中的链接
- 不能让函数改变变量
- Javascript滑块动态改变变量
- 通过html按钮改变变量
- Jquery在点击时改变变量
- 不能改变变量
- 为什么我的精灵在不改变变量的情况下加速
- 在javascript的文字函数中改变变量的值
- jQuery用子元素改变变量
- 改变变量&设置日期反应原生
- Ajax文件检查成功后不改变变量