我使用jQuery来处理ajax调用。我注意到,大约5%的ajax调用失败。为了确保我很好地理解出了什么问题,我使用以下代码:
$.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;
}
});
"Good"响应包含JSON,我将对其进行解析。如果它不是JSON(例如php错误的原始文本),我不会尝试解析它,而是将错误存储在我的数据库中。
我可以理解在somepage.php上发生的包含php错误的错误(因为它是一个大页面),但我惊讶的是,我得到的主要错误是ajax失败的错误。响应数据为"error".
有人知道原因是什么吗?是什么导致ajax调用失败?它是而不是超时,也不像somepage.php找不到之类的。在somepage.php上也不是错误,因为在这种情况下,ajax调用将成功,并且php错误将记录在我的数据库中。
编辑:我使用这个混淆器使脚本更难阅读…
您应该在ajax调用中设置dataType: 'json'
。因为如果你没有设置这个,并且你期望一个json结果,结果将默认被视为'string'。