jQuery Ajax, overwrite onreadystatechange handler

前端 未结 3 1195
离开以前
离开以前 2020-12-10 08:57

I\'m recently fooling around with some ajax polling techniques. However, it seems like I can\'t overwrite the onreadystatechange handler from a XMLHttpReq

相关标签:
3条回答
  • 2020-12-10 09:27

    If you want a large level of customization, you can just get the XMLHttpRequest object and control it yourself.

    var x=new $.ajaxSettings.xhr();
    x.onreadystatechange=function(){ ... }
    ...
    
    0 讨论(0)
  • 2020-12-10 09:31

    I agree with Maz here, you can still benefit form the query handling and creating of the object, and also no need to patch jquery for this

    however, if you dont mind patching jquery you could add these lines

            // The readystate 2
            } else if ( !requestDone && xhr && xhr.readyState === 2 && isTimeout !== 'timeout' && s.state2) {
                s.state2.call( s.context, data, status, xhr );
            // The readystate 3
            } else if ( !requestDone && xhr && xhr.readyState === 3 && isTimeout !== 'timeout' && s.state3) {
                s.state3.call( s.context, data, status, xhr );
    

    before this line: (jQuery v 1.4.4) or just search for the readyState === 4 in the source

            // The transfer is complete and the data is available, or the request timed out
            } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
    

    now you can use the $.ajax again and put a handler up for state2 and state3 like so:

    $.ajax({
        url: 'http://www.stackoverflow.com',
        cache: false,
        success:function(){console.log('success');},
        error: function (){console.log('error');},
        complete: function (){console.log('complete');},
        state2: function (context,data,status,xhr) {console.log('state2');},
        state3: function (context,data,status,xhr) {console.log('state3');}
    });
    

    it doesnt exactly behave like the other handlers, eg returngin false wont do a thing but you can still handle the xhr object and abort that way

    ill see if i can submit this to be included in the source later this day, who knows they might accept it

    0 讨论(0)
  • 2020-12-10 09:31

    You can do this by doing something like that:

    $.ajax({
    type: "POST",
    url: "Test.ashx",
    data: { "command": "test" },
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType: "json",
    beforeSend: function (request, settings) {
        $(request).bind("readystatechange", function (e) { alert("changed " + e.target.readyState); });
    }});
    
    0 讨论(0)
提交回复
热议问题