我有这个 javascript 代码:
$(function() {
    $("<img>", {
        src: "http://urlpath/img.png",
        error: function() { alert("error!"); },
        load: function() { alert("ok"); }
    });
});
它的代码有效,但我需要为此请求设置超时以避免请求缓慢。
任何建议都会对我有用!
感谢:D
我有这个 javascript 代码:
$(function() {
    $("<img>", {
        src: "http://urlpath/img.png",
        error: function() { alert("error!"); },
        load: function() { alert("ok"); }
    });
});
它的代码有效,但我需要为此请求设置超时以避免请求缓慢。
任何建议都会对我有用!
感谢:D
$(function() {
    timedout = false;
    var i = $("<img>", {
        src: "http://urlpath/img.png",
        error: function() { if (!timedout) { timedout = true; alert("error!"); } },
        load: function() { timedout = true; alert("ok"); }
    });
    window.setTimeout(function () { i.trigger('error'); i.remove(); }, 2000);
});
尝试这个:
$(function() {
    var timed = false;
    var imgTO = setTimeout(function () {
        timed = true;
        alert("timed out");
    }, 2000);  // 2 second timeout
    $("<img>").on({
        error: function() {
            clearTimeout(imgTO);
            if (!timed) alert("error!");
        },
        load: function() {
            clearTimeout(imgTO);
            if (!timed) alert("ok");
        }
    }).attr("src", "http://urlpath/img.png");
});
也许你需要:
$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});
[阅读] http://api.jquery.com/jQuery.ajax/
您可以将超时指定为属性。