1

私の質問は非常に基本的なものかもしれませんが、かなり長い間それに固執しています。

YAHOO.util.connect.asyncRequest または jquery または単純な XMLHttpRequest の $.ajax() であるかどうかにかかわらず、インターフェイスを介して行われた ajax 呼び出しの開始または完了を知る必要があるアプリケーションがあります。

私が試してみました

$(document).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
})

しかし、jquery ajax関数からトリガーされるイベントのみをバインドすると思います

4

1 に答える 1

1

この回答のように、ページ上のすべてのAJAXリクエストに「フック」を追加すると、そのコードを見て試してみることができます。

コードは、(jQuery だけでなく) ajax 呼び出しごとに JavaScript でフックし、独自のハンドラーを定義できるようにします。

function addXMLRequestCallback(callback){
    var oldSend, i;
    if( XMLHttpRequest.callbacks ) {
        // we've already overridden send() so just add the callback
        XMLHttpRequest.callbacks.push( callback );
    } else {
        // create a callback queue
        XMLHttpRequest.callbacks = [callback];
        // store the native send()
        oldSend = XMLHttpRequest.prototype.send;
        // override the native send()
        XMLHttpRequest.prototype.send = function(){
            // process the callback queue
            // the xhr instance is passed into each callback but seems pretty useless
            // you can't tell what its destination is or call abort() without an error
            // so only really good for logging that a request has happened
            // I could be wrong, I hope so...
            // EDIT: I suppose you could override the onreadystatechange handler though
            for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
                XMLHttpRequest.callbacks[i]( this );
            }
            // call the native send()
            oldSend.apply(this, arguments);
        }
    }
}

// e.g.
addXMLRequestCallback( function( xhr ) {
    console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( xhr ) {
    console.dir( xhr ); // have a look if there is anything useful here
});
于 2013-04-06T10:45:59.597 に答える