Javascript jQuery的AJAX计时问题

Javascript jQuery的AJAX计时问题,javascript,jquery,asp.net,ajax,Javascript,Jquery,Asp.net,Ajax,我到处都找遍了,我已经为此工作了几个小时。基本上,我有一个Ajax调用,从一个从数据库获取数据的网页获取数据。此代码用于图像库的幻灯片放映。整个函数如下所示,但是,无法正常工作的部分是获取图像高度和宽度的两行代码 图像被正确地获取,并且显示得很好(虽然不是真的,但是它们显示出来了)。查询图像宽度和高度的行大部分时间返回0。它们返回正确值的概率约为5%。这会导致直接在后面的if语句总是求值为false,这会使宽图像延伸到网页边缘之外 这个问题只存在于基于Webkit的浏览器中。基于Gecko的浏览

我到处都找遍了,我已经为此工作了几个小时。基本上,我有一个Ajax调用,从一个从数据库获取数据的网页获取数据。此代码用于图像库的幻灯片放映。整个函数如下所示,但是,无法正常工作的部分是获取图像高度和宽度的两行代码

图像被正确地获取,并且显示得很好(虽然不是真的,但是它们显示出来了)。查询图像宽度和高度的行大部分时间返回0。它们返回正确值的概率约为5%。这会导致直接在后面的if语句总是求值为false,这会使宽图像延伸到网页边缘之外

这个问题只存在于基于Webkit的浏览器中。基于Gecko的浏览器没有这个问题

我认为问题在于jQuery试图在Ajax调用完成其请求之前查询图像。有没有办法让jQuery等待Ajax完成其请求

function LoadForm() {
    GalleryDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: BaseAPI + "/PhotosByAlbum2",
                dataType: "json",
                data: { "location": locationID, "ID": $.getQuery('ID') }
            }
        }
    });

    $("#slides").kendoListView({
        dataSource: GalleryDataSource,
        template: kendo.template($("#SlidesTemplate").html())
        });

    $.ajax({
        type: "Get",
        contentType: "application/json; charset=utf-8",
        url: BaseAPI + "/PhotosByAlbum2",
        datatype: "json",
        data: { "location": locationID, "ID": $.getQuery('ID') },
        success: function (d) {
            for (var i = 0; i < d.length; i++) {
                $('#Show').append(
                    '<figure><img src="' + d[i].Path +
                    '" id="' + d[i].ID +
                    '"/><figcaption>Title: ' + d[i].Title + '<br />' +
                    'Description: ' + d[i].Description +
                    '</figcaption></figure>'
                );

/*these do*/    var imgheight = $("#" + d[i].ID).height();
/*not work*/    var imgwidth = $("#" + d[i].ID).width();

                if (imgheight < "768" && imgwidth > imgheight) {
                    $("#" + d[i].ID).addClass("wideimage");
                } else {
                    $("#" + d[i].ID).addClass("tallimage");
                }
            }

            $('#Show').innerfade({
                animationtype: 'fade',
                speed: 1050,
                timeout: 2000,
                type: 'sequence',
                containerheight: '500px'
            });
        }
    });

    $('#back').click(function () {
        window.location = 'Photos.aspx'
    });
}
函数加载形式(){
GalleryDataSource=新建kendo.data.DataSource({
运输:{
阅读:{
url:BaseAPI+“/PhotosByAlbum2”,
数据类型:“json”,
数据:{“location”:locationID,“ID”:$.getQuery('ID')}
}
}
});
$(“#幻灯片”).kendoListView({
数据源:GalleryDataSource,
模板:kendo.template($(“#SlidesTemplate”).html()
});
$.ajax({
键入:“获取”,
contentType:“应用程序/json;字符集=utf-8”,
url:BaseAPI+“/PhotosByAlbum2”,
数据类型:“json”,
数据:{“location”:locationID,“ID”:$.getQuery('ID')},
成功:功能(d){
对于(变量i=0;i'+
'说明:'+d[i].说明+
''
);
/*这些do*/var imgheight=$(“#”+d[i].ID).height();
/*不工作*/var imgwidth=$(“#”+d[i].ID).width();
如果(imgheight<“768”和&imgwidth>imgheight){
$(“#”+d[i].ID).addClass(“wideimage”);
}否则{
$(“#”+d[i].ID).addClass(“tallimage”);
}
}
$('#Show')。内部淡入淡出({
animationtype:“淡入淡出”,
速度:1050,
超时时间:2000,
类型:'序列',
集装箱重量:“500px”
});
}
});
$('#返回')。单击(函数(){
window.location='Photos.aspx'
});
}
注意:我尝试过使用
$.when(*ajax call here*).done(function(){*do stuff*})。它的表现完全一样

我尝试将
async
选项设置为false。同样的行为


我还尝试在Ajax调用中添加
complete
事件处理程序。同样,它的行为也是如此。

正如我在评论中所说的,您必须等待图像加载,然后才能可靠地获得图像的宽度并设置所需的类

下面是一种重新构造ajax调用的方法,以便仅在图像加载后处理图像,并且仅在图像全部加载并正确标记后启动动画:

$.ajax({
    type: "Get",
    contentType: "application/json; charset=utf-8",
    url: BaseAPI + "/PhotosByAlbum2",
    datatype: "json",
    data: { "location": locationID, "ID": $.getQuery('ID') },
    success: function (d) {
        var imagesRemaining = d.length;
        for (var i = 0; i < d.length; i++) {
            var img = new Image();
            img.src = d[i].Path;
            img.id = d[i].ID;
            img.onload = function() {
                --imagesRemaining;
                var item = $(this);
                var imgheight = item.height();
                var imgwidth = item.width();

                if (imgheight < 768 && imgwidth > imgheight) {
                    item.addClass("wideimage");
                } else {
                    item.addClass("tallimage");
                }

                // now see if all images are loaded now
                // so all classes are set so we can now start the animation
                if (imagesRemaining === 0) {
                    $('#Show').innerfade({
                        animationtype: 'fade',
                        speed: 1050,
                        timeout: 2000,
                        type: 'sequence',
                        containerheight: '500px'
                    });
                }
            };
            $("<figure>").append(img).append('<figcaption>Title: ' + d[i].Title + '<br />' +
                'Description: ' + d[i].Description + '</figcaption>').appendTo("#Show");

        }

    }
});
$.ajax({
键入:“获取”,
contentType:“应用程序/json;字符集=utf-8”,
url:BaseAPI+“/PhotosByAlbum2”,
数据类型:“json”,
数据:{“location”:locationID,“ID”:$.getQuery('ID')},
成功:功能(d){
var imagesRemaining=d.长度;
对于(变量i=0;iimgheight){
项目。addClass(“wideimage”);
}否则{
项目.addClass(“tallimage”);
}
//现在查看是否已加载所有图像
//所有的类都设置好了,现在我们可以开始动画了
如果(图像保留===0){
$('#Show')。内部淡入淡出({
animationtype:“淡入淡出”,
速度:1050,
超时时间:2000,
类型:'序列',
集装箱重量:“500px”
});
}
};
$(“”).append(img).append('Title:'+d[i].Title+'
+ 'Description:'+d[i].Description+'')。附录(“#Show”); } } });
如注释中所述,在加载图像之前,您无法访问图像的高度和宽度。我将执行以下操作以侦听加载事件:

$.each(d, function (idx, item) {
    $fig = $('<figure/>');
    $('<figcaption/>')
        .html('Title: ' + item.Title + '<br />Description: ' + item.Description)
        .appendTo($fig);

    $('<img/>')
        .load(function () {
            var $this = $(this);
            var height = $this.height();
            var width = $this.width();
            if (height < "768" && width > height) {
                $this.addClass('wideimage');
            } else {
                $this.addClass('tallimage');
            }
        }).attr('id', item.ID)
        .attr('src', item.Path)
        .appendTo($fig);

    $fig.appendTo('#Show');
});
$。每个(d,函数(idx,项){
$fig=$('');
$('')
.html('Title:'+item.Title+'
说明:'+item.Description) .appendTo($fig);
$('我这样做了……当然,还有更好的方法

在以BaseAPI+“/PhotosByAlbum2”运行的php脚本中…获取每个图像的宽度和高度,根据需要将图像调整为幻灯片的正确高度和宽度,然后将这些变量放入结果数组中,并带有路径、标题和说明


在jQuery上…读取数组并调整html中的宽度和高度…

如果要在计算中使用图像尺寸,则在成功下载图像之前无法运行该代码。并且,知道何时发生这种情况的唯一方法是对图像本身使用
onload
处理程序。如果那么,代码现在在任何地方都可以工作了