gpt4 book ai didi

javascript - Ajax 有 5% 的时间失败,响应为 "error"

转载 作者:行者123 更新时间:2023-12-01 05:47:53 26 4
gpt4 key购买 nike

我使用 jQuery 来处理 Ajax 调用。我注意到,ajax 调用失败的概率大约为 5%。为了确保我很好地理解出了什么问题,我使用了以下代码:

$.ajax({

type:'POST',
url:'somepage.php',
data:{somedata:somedata},
success:function (data) {

var IS_JSON = true;

try
{
var newdata = jQuery.parseJSON(data);
}
catch(err)
{
IS_JSON = false;
}

if(IS_JSON)
{
//this is the part where a correct response is handled

}
else
{
//In case somepage.php gives a php-error, I put the exact error (=data) in the error-table at error.php.
window.location = "error.php?errorstring="+data;
}


},
error:function (XMLHttpRequest, textStatus, errorThrown) {
//In case the ajax errors, I store the response (timeout, error, ...) in the database at error.php
window.location = "error.php?errorstring="+textStatus;

}

});

“良好”响应包含我解析的 JSON。如果它不是 JSON(例如只是来自 php 错误的原始文本),我不会尝试解析它,而是将错误存储在我的数据库中。

我会理解包含 somepage.php 上发生的 php 错误的错误(因为它是一个安静的大页面),但我很惊讶我得到的主要错误是 ajax 失败的错误。响应数据只是“错误”。

有谁知道这可能是什么原因吗? 什么原因导致 ajax 调用失败?这不是超时,也不是找不到 somepage.php 之类的。这也不是 somepage.php 上的错误,因为在这种情况下,Ajax 调用将成功,并且 php 错误将记录在我的数据库中。

编辑:我用了 this混淆器使脚本有点难以阅读...不知道这是否会导致错误...

最佳答案

您应该在 ajax 调用中设置 dataType: 'json'。因为如果您没有设置它并且您期望 json 结果,则默认情况下结果将被视为“字符串”。

关于javascript - Ajax 有 5% 的时间失败,响应为 "error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043909/

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