Method POST, Status (canceled) error message

家住魔仙堡 提交于 2019-12-21 07:45:56

问题


I have the following code which is giving me a Method POST, Status (canceled) error message:

$(document).ready(function() {
    var xhr = false;

    get_default();

    $('#txt1').keyup( function() {
        if(xhr && xhr.readyState != 4){
            alert("abort");
            xhr.abort();
        }

        if ($("#txt1").val().length >= 2) {
            get_data( $("#txt1").val() );
        } else {
            get_default();
        }
    });

    function get_data( phrase ) {
        xhr = $.ajax({
            type: 'POST',
            url: 'http://intranet/webservices.asmx/GetData',
            data: '{phrase: "' + phrase + '"}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function( results ) {
                $("#div1").empty();

                if( results.d[0] ) {
                    $.each( results.d, function( index, result ) {
                        $("#div1").append( result.Col1 + ' ' + result.Col2 + '<br />' );
                    });
                } else {
                    alert( "no data available message goes here" );
                }
            },
            error: function(xhr, status, error) {
                 var err = eval("(" + xhr.responseText + ")");
                 alert(err.Message) ;
            }
        });
    }

    function get_default() {
        $('#div1').empty().append("default content goes here.");
    }

});

The code actually works as long as each ajax request completes, but if I type fast into txt1, i.e. type the next character before the previous request finishes, I get the error message Method POST, Status (canceled).

Anyone know why this is happening and how to correct the error?


回答1:


I suppose that the problem is very easy. If you call xhr.abort(); then the error callback of $.ajax will be called for the pending request. So you should just ignore such case inside of error callback. So the error handler can be modified to

error: function(jqXHR, textStatus, errorThrown) {
    var err;
    if (textStatus !== "abort" && errorThrown !== "abort") {
        try {
            err = $.parseJSON(jqXHR.responseText);
            alert(err.Message);
        } catch(e) {
            alert("ERROR:\n" + jqXHR.responseText);
        }
    }
    // aborted requests should be just ignored and no error message be displayed
}

P.S. Probably another my old answer on the close problem could also interesting for you.




回答2:


That is because you are calling abort method which possibly triggers the error handler with appropriate error message.

You can possibly wait for previous ajax request to complete before making the next call.




回答3:


In order to both fix your problem and save on the amount of Ajax calls I have written the following example. This example allows you to handle the following two situations:

Situation 1:

The user types slow enough (lets say about one key every 200+ miliseconds

Situation 2:

The user types fast (my average is about 20 to 50 miliseconds per key)

In the following example there is no need to abort or ignore Ajax calls, you are not spamming Ajax calls and you are using an Object to handle your job. (I even jsFiddled it for you)

var Handler = {

    /**
     * Time in ms from the last event
     */
    lastEvent: 0,

    /**
     * The last keystroke must be at least this amount of ms ago
     * to allow our ajax call to run
     */
    cooldownPeriod: 200,

    /**
     * This is our timer
     */
    timer: null,

    /**
     * This should run when the keyup event is triggered
     */
    up: function( event )
    {
        var d = new Date(),
            now = d.getTime();

        if( ( now - Handler.lastEvent ) < Handler.cooldownPeriod ) {
           // We do not want to run the Ajax call
            // We (re)set our timer
            Handler.setTimer();
        } else {
            // We do not care about our timer and just do the Ajax call
            Handler.resetTimer();
            Handler.ajaxCall();
        }

        Handler.lastEvent = now;
    },

    /**
     * Function for setting our timer
     */
    setTimer: function()
    {
        this.resetTimer();
        this.timer = setTimeout( function(){ Handler.ajaxCall() }, this.cooldownPeriod );
    },

    /**
     * Function for resetting our timer
     */
    resetTimer: function()
    {
        clearTimeout( this.timer );
    },

    /**
     * The ajax call
     */
    ajaxCall: function()
    {
        // do ajax call
    }

};

jQuery( function(){

    var field = jQuery( '#field' );

    field.on( 'keyup', Handler.up );

});

Hope this helps.




回答4:


You are using the keyup event, which seems to be the problem.

If anything at all, you need to wait after typing one character before taking action.

A better solution might be to follow the same strategy as the JQuery AutoComplete COmponent.




回答5:


Ajax is an async type, its not recommonded that u to send request on every keyup event, try the...

async: false

in post method... it'll pause the subsequent posts until the current request done its callback




回答6:


Realistically you need a setTimeout method in order to prevent redundant ajax calls being fired.

clearTimeout(timer);

if($("#txt1").val().length >= 2){
    timer = setTimeout(function(){
        get_data($("#txt1").val());
    }, 400);
}else{
    get_default();
}

This should eradicate your problem.



来源:https://stackoverflow.com/questions/9928580/method-post-status-canceled-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!