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?
Answer1:
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.
Answer2:
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.
Answer3:
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
【转载】http://stackoverflow.com/questions/9928580/method-post-status-canceled-error-message