質問

.load() が 5 秒以内に返らない場合、.load() 操作をキャンセルしたいと考えています。その場合は、「申し訳ありません、画像が読み込まれていません」のようなエラー メッセージを表示します。

私が持っているものは...

...タイムアウト処理:

jQuery.fn.idle = function(time, postFunction){  
    var i = $(this);  
    i.queue(function(){  
        setTimeout(function(){  
            i.dequeue();
            postFunction();  
        }, time);  
    });
    return $(this); 
};

...エラーメッセージタイムアウトの初期化:

var hasImage = false;

$('#errorMessage')
    .idle(5000, function() {

        if(!hasImage) {
            // 1. cancel .load()            
            // 2. show error message
        }
    });

...画像の読み込み:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .load(function(){
         hasImage = true;
         // do something...
      });

私が理解できなかった唯一のことは、実行中のload()をキャンセルする方法です(可能であれば)。

編集:

別の方法:.load() メソッドが戻るときにコールバック関数を呼び出さないようにするにはどうすればよいですか?

役に立ちましたか?

解決

あなたはこのような取扱い任意のカスタムをしたい場合、あなたは、単にjQuery.load()関数を使用することはできません。あなたはエラー処理のいずれかの種類を必要とする場合は特に、それが必要になります、あなたはそんなに多くのそれを行うことができますので、私はとにかくお勧めjQuery.ajax()にアップグレードする必要があります。

jQuery.ajaxためbeforeSendオプションを使用し、XHRをキャプチャします。そして、あなたはタイムアウト後XHRをキャンセルすることができ、コールバック、および必要に応じてコールバックを作成することができます。

このコードはテストされていませんが、あなたが始める必要があります。

var enableCallbacks = true;
var timeout = null;
jQuery.ajax({
  ....
  beforeSend: function(xhr) {
    timeout = setTimeout(function() {
      xhr.abort();
      enableCallbacks = false;
      // Handle the timeout
      ...
    }, 5000);
  },
  error: function(xhr, textStatus, errorThrown) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle other (non-timeout) errors
  },
  success: function(data, textStatus) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle the result
    ...
  }
});

他のヒント

あなたの言い換え二次の質問:
をどのように私は保留中キャンセルんコールバック関数、.LOAD()メソッドを使用して作成された?

あなたがこの「核」オプションを使用することにより、すべてのjqueryのコールバックをキャンセルすることができます:

$('#myImage').unbind('load');

私は、最も簡単な方法は、直接$.ajaxを使用することだと思います。そうすれば、あなたはタイムアウトを開始し、タイムアウトからAJAX呼び出しのハンドラがチェックできるというフラグを設定することができます。タイムアウトは、メッセージまたは何を表示することができます。

このコードを読み込む場合はJQueryがされた後は、あなたがタイムアウトパラメータと.LOAD()を呼び出すことができます読み込まれます。

jQuery.fn.load = function( url, params, callback, timeout ) {
    if ( typeof url !== "string" ) {
        return _load.call( this, url );

    // Don't do a request if no elements are being requested
    } else if ( !this.length ) {
        return this;
    }

    var off = url.indexOf(" ");
    if ( off >= 0 ) {
        var selector = url.slice(off, url.length);
        url = url.slice(0, off);
    }

    // Default to a GET request
    var type = "GET";

    // If the second parameter was provided
    if ( params ) {
        // If it's a function
        if ( jQuery.isFunction( params ) ) {
            if( callback && typeof callback === "number"){
                timeout = callback;
                callback = params;
                params = null;
            }else{
                // We assume that it's the callback
                callback = params;
                params = null;
                timeout = 0;
            }
        // Otherwise, build a param string
        } else if( typeof params === "number"){
            timeout = params;
            callback = null;
            params = null;
        }else if ( typeof params === "object" ) {
            params = jQuery.param( params, jQuery.ajaxSettings.traditional );
            type = "POST";
            if( callback && typeof callback === "number"){
                timeout = callback;
                callback = null;
            }else if(! timeout){
                timeout = 0;
            }
        }
    }

    var self = this;

    // Request the remote document
    jQuery.ajax({
        url: url,
        type: type,
        dataType: "html",
        data: params,
        timeout: timeout,
        complete: function( res, status ) {
            // If successful, inject the HTML into all the matched elements
            if ( status === "success" || status === "notmodified" ) {
                // See if a selector was specified
                self.html( selector ?
                    // Create a dummy div to hold the results
                    jQuery("<div />")
                        // inject the contents of the document in, removing the scripts
                        // to avoid any 'Permission Denied' errors in IE
                        .append(res.responseText.replace(rscript, ""))

                        // Locate the specified elements
                        .find(selector) :

                    // If not, just inject the full result
                    res.responseText );
            }

            if ( callback ) {
                self.each( callback, [res.responseText, status, res] );
            }
        }
    });

    return this;
};

わからない何か「標準」jQueryの関数を上書きすることに興味があるが、これはあなたが)(あなたが説明した方法を.LOAD使用できるようになります。

私はあなたがここからそこに着くことができるとは思わない - @Pointyが述べたように、あなたがそれに.abort()メソッドにアクセスできるようにXmlHttpRequestのオブジェクトを取得する必要がありますする必要があります。そのために、あなたはあなたにオブジェクトを返す.ajax() jQueryのAPIを必要とします。

は、要求を中止する能力がなければ、考慮すべきもう一つの方法は、コールバック関数にタイムアウトの知識を追加することです。あなたは、この2つの方法で行うことができます - 最初ます:

var hasImage = false;

$('#errorMessage')
    .idle(5000, function() {

        if(!hasImage) {
            // 1. cancel .load()            
            // 2. show error message
            // 3. Add an aborted flag onto the element(s)
            $('#myImage').data("aborted", true);
        }
    });

そして、あなたのコールバックます:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .load(function(){
         if($(this).data("aborted")){
             $(this).removeData("aborted");
             return;
         }
         hasImage = true;
         // do something...
      });

それとも、この特定の機能のためにアイドルを回避できます:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .data("start", (new Date()).getTime())
     .load(function(){
         var start = $(this).data("start");
         $(this).removeData("start");
         if(((new Date()).getTime() - start) > 5000)
             return;

         hasImage = true;
         // do something...
      });

どちらのアプローチが理想的ですが、私はあなたが直接jQueryの1.4のような負荷を取り消すことができるとは思わない - 。、jQueryのチームに素敵な機能要求かもしれませんが、

$('#myImage').load(function(){...}) は画像をロードするための関数呼び出しではなく、実際にはコールバックを onload イベント.

したがって、 timeout パラメータへの .load() 方法 他の回答で示唆されているように、効果はありません。

次の 2 つの選択肢があると考えられます。

  1. あなたがフォローしている道を続けて、$('#myImage').attr('src', ''); 画像の負荷をキャンセルしてから外出した後、または

  2. 何か使い道を見つけてください $.ajax( { ... , timeout: 5000, ...} ); ブラウザに自動的に実行させる代わりに、画像をロードするには<img src="..."> 属性。

あなたは、単に画像をロードするだけでなく、ロード・エラーのためにテストする前にタイムアウトを設定することができます。

function LoadImage(yourImage) {

    var imageTimer = setTimeout(function () {
        //image could not be loaded:
        alert('image load timed out');
    }, 10000); //10 seconds

    $(yourImage).load(function (response, status, xhr) {
        if (imageTimer) {

            if (status == 'error') {
                //image could not be loaded:
                alert('failed to load image');

            } else {
                //image was loaded:
                clearTimeout(imageTimer);
                //display your image...
            }

        }
    });

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top