是否可以在jQuery.post()上检查超时?

hor*_*gen 9 ajax jquery timeout

我有这个代码从mysql DB请求一些文件夹信息:

function gotoDir(pmcat_id, pcat_id){
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.post("/publish/includes/content.includes/functions.slideshow.php", 
        {  updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        function(data){
             $('#pageSlideshow').html(data.content);
        }, "json"
    );
}
Run Code Online (Sandbox Code Playgroud)

有时,由于互联网连接不良,帖子请求超时.是否可以在$ .post()上设置超时检查?例如:如果$ .post()使用多于X ms,则重新加载请求.

更新:看起来我找到了一个解决方案:

function gotoDir(pmcat_id, pcat_id){
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.ajax({
        type:"post",
        url:"/publish/includes/content.includes/functions.slideshow.php",
        data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        dataType: "json",
        success:function(data) {
            if (data == null){
            alert('ajax failed. reloading...');
            gotoDir(pmcat_id, pcat_id);
        } else {
            $('#pageSlideshow').html(data.content);
        }
        }        
    });
}
Run Code Online (Sandbox Code Playgroud)

这是一个可行的方法吗?:S

ifa*_*our 29

$ .ajax具有完成所要求的所有功能:

function gotoDir(pmcat_id, pcat_id) {
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.ajax({
        type: "POST",
        url: "/publish/includes/content.includes/functions.slideshow.php",
        data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        dataType: "json",
        timeout: 500, // in milliseconds
        success: function(data) {
            // process data here
        },
        error: function(request, status, err) {
            if(status == "timeout") {
                gotoDir(pmcat_id, pcat_id);
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要设置超时时间,除非你想有一个特定的时间后触发错误方法选择想要设置.


Mat*_*uke 3

您应该使用$.ajax()$.ajaxError(),然后使用“ajaxComplete”您可以检查您的请求是否为timedout, 或succeded

来源:jQuery API