javascript 方法 POST、状态(已取消)错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9928580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method POST, Status (canceled) error message
提问by oshirowanen
I have the following code which is giving me a Method POST, Status (canceled)
error message:
我有以下代码,它给了我一条Method POST, Status (canceled)
错误消息:
$(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)
.
只要每个ajax请求完成,代码实际上就可以工作,但是如果我快速输入txt1
,即在上一个请求完成之前输入下一个字符,我会收到错误消息Method POST, Status (canceled)
。
Anyone know why this is happening and how to correct the error?
任何人都知道为什么会发生这种情况以及如何纠正错误?
采纳答案by Oleg
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
我想这个问题很容易。如果您调用,则将为挂起的请求调用xhr.abort();
的error
回调。所以你应该忽略回调内部的这种情况。所以处理程序可以修改为$.ajax
error
error
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 answeron the close problem could also interesting for you.
PS 可能我对关闭问题的另一个旧答案也可能对您感兴趣。
回答by ShankarSangoli
That is because you are calling abort
method which possibly triggers the error handler with appropriate error message.
那是因为您正在调用abort
可能会触发带有适当错误消息的错误处理程序的方法。
You can possibly wait for previous ajax request to complete before making the next call.
您可以在进行下一次调用之前等待上一个 ajax 请求完成。
回答by Yogesh Prajapati
You are using the keyup
event, which seems to be the problem.
您正在使用该keyup
事件,这似乎是问题所在。
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
.
更好的解决方案可能是遵循与JQuery AutoComplete COmponent
.
回答by halfpastfour.am
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:
为了解决您的问题并节省 Ajax 调用的数量,我编写了以下示例。本示例允许您处理以下两种情况:
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 jsFiddledit for you)
在以下示例中,无需中止或忽略 Ajax 调用,您不是在发送垃圾邮件 Ajax 调用,而是使用对象来处理您的工作。(我什至jsFiddled给你)
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.
希望这可以帮助。
回答by Dasarp
Ajax is an async type, its not recommonded that u to send request on every keyup event, try the...
Ajax 是一种异步类型,不建议您在每个 keyup 事件上发送请求,尝试...
async: false
in post method... it'll pause the subsequent posts until the current request done its callback
在 post 方法中......它会暂停后续的帖子,直到当前请求完成它的回调
回答by trickyzter
Realistically you need a setTimeout method in order to prevent redundant ajax calls being fired.
实际上,您需要一个 setTimeout 方法来防止触发多余的 ajax 调用。
clearTimeout(timer);
if($("#txt1").val().length >= 2){
timer = setTimeout(function(){
get_data($("#txt1").val());
}, 400);
}else{
get_default();
}
This should eradicate your problem.
这应该可以解决您的问题。