0

このシナリオに非jqueryソリューションがあるかどうか疑問に思っていました:

サーバーのインターネット接続がダウンしたか、クライアントのインターネット接続がダウンしたか、サーバーがクラッシュしたため、ajax 要求に対する応答がありません。この問題に役立つメソッド/イベントが xmlhttprequest オブジェクトに組み込まれていますか?

4

1 に答える 1

1

タイムアウト プロパティを設定できます。

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            done(request.responseText);
        }
    },
    done = function (response) { console.log(response) },
    fail = function () {};

    xhr.open("GET", "url", true);
    xhr.timeout = 4000;
    xhr.ontimeout = function () { xhr.abort(); fail(); }
    xhr.send();

または単に使用するwindow.setTimeout

var xhr = new XMLHttpRequest(),
    timeout;

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            done(request.responseText);
            clearTimeout(timeout);
        }
    };

    xhr.open("GET", "url", true);
    xhr.timeout = 4000;
    xhr.ontimeout = function () { xhr.abort(); fail(); }
    xhr.send();
    timeout = window.setTimeout(function () { xhr.abort() }, 4000);
于 2013-01-26T01:18:33.637 に答える