gpt4 book ai didi

javascript - else 子句重复 ajax 触发器太多次

转载 作者:行者123 更新时间:2023-11-30 16:53:02 25 4
gpt4 key购买 nike

我的网站上有一个调用 cgi 脚本的 ajax 函数。此脚本很少会返回 500 错误。我正在尝试更改 AJAX 调用,以便在发生这种情况时重复请求。我试过这样做:

function shelverx() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}

我想知道是否有更好的方法来实现这一点?我发现发生的情况是,每当出现 500 错误时,即使第二次调用成功,也会调用 shelverx 函数四次。有没有办法让每个错误只重复调用一次?

我还尝试通过将整个 ajax 调用更改为 jQuery 并使用以下错误函数来完成同样的事情:

error: function(xhr, textStatus, errorThrown ) {
this.tryCount++;
if (this.tryCount<=this.retryLimit) {
$.ajax(this);
return;
}

但是我得到了一个 Unexpected Token : 错误。如果有人可以帮助我使这些方法中的任何一种起作用,我将不胜感激。我的目标是让 ajax 调用每 500 次错误只重复一次。

最佳答案

乔纳森 -

下面的代码片段可以如您所愿。计数器在调用之间保持其值并在 5 停止请求。我还更改了 IF 语句逻辑并添加了一个计时器以在两次尝试之间等待 1 秒。试一试。

请注意,原始逻辑无法正常工作。在调试器中,它会根据每个请求多次递增计数器。在 readyState = 4 之后检查状态会更好。

原代码:

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}

测试和工作示例:

<!doctype html>
<html>
<body>

<script type="text/javascript">

var postdata = '';
var filepath = 'NothingHere.html';
var limit = 0;

function shelverx() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.info('Success: Recieved ' + xmlhttp.responseText.length + ' bytes');
}
else {
limit++;
console.info( 'Error: ' + xmlhttp.status + ':' + xmlhttp.statusText );
if (limit < 5) setTimeout( shelverx, 1000 );
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}

shelverx();

</script>
</body>
</html>

关于javascript - else 子句重复 ajax 触发器太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com