我有一个网页,javascript通过.ajax()函数使用POST请求调用PHP服务器。PHP服务器反过来调用外部第三方API来提交文本分析作业。处理完文本分析作业后,我的PHP服务器将查询API的结果。但是,第三方REST API不提供任何查询作业状态的方法。因此,在我提交作业后,我让程序休眠大约一分钟,然后查询结果。然而,有时我的结果是不完整的。我尝试将睡眠时间设置为较大,但将其设置为超过一分钟似乎会使从Javascript到PHP的初始POST请求超时。将ajax超时参数设置为高并没有帮助。有人对如何解决这个问题有什么建议吗?非常感谢您的帮助。
ajax请求如下所示:
function callServer(params, success) {
var url = "ie.php";
$.ajax({
type: 'POST',
url: url,
data: params,
timeout: 60000000, //time out parameter doesn't work
dataType: "json",
success: function(result, textStatus) {
console.log(JSON.stringify(result, null, ' '));
if (success) success(result);
},
error: function(xhr, textStatus, errorThrown) {
var text = 'Ajax Request Error: ' + 'XMLHTTPRequestObject status: ('+xhr.status + ', ' + xhr.statusText+'), ' +
'text status: ('+textStatus+'), error thrown: ('+errorThrown+')';
console.log('The AJAX request failed with the error: ' + text);
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
}
});
}
错误如下:
AJAX请求失败,返回错误:AJAX请求错误:XMLHTTPRequestObject状态:(0,error),文本状态:(error),抛出错误:()
整个过程中有多个地方有超时设置:
- Browser/Ajax调用
- PHP有自己的:
ini_set('max_execution_time', '1800');
或set_time_limit(1800);
- Apache本身有一个最大运行时间:超时
apache2.conf
- 可能是您的REST API-无论您如何调用它
在我看来,最好的情况是从阻塞/同步策略更改为异步策略:
- 使用ajax将请求从客户端发送到服务器
- 从服务器异步运行REST API(查找异步curl或node.js)
- 客户端使用ajax定期查询服务器的状态(可能每10秒一次)
这使得整个过程异步,并且在处理发生时不需要等待或阻止
你能做到吗?
function callServer(params, success) {
var url = "ie.php";
setTimeout(function(){
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: "json",
success: function(result, textStatus) {
console.log(JSON.stringify(result, null, ' '));
if (success) success(result);
},
error: function(xhr, textStatus, errorThrown) {
var text = 'Ajax Request Error: ' + 'XMLHTTPRequestObject status: ('+xhr.status + ', ' + xhr.statusText+'), ' +
'text status: ('+textStatus+'), error thrown: ('+errorThrown+')';
console.log('The AJAX request failed with the error: ' + text);
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
}
})
}, 200);
}
要修复这样的超时错误,需要在3或4个不同的地方设置超时长度:
-
Jquery本身(可以像您一样使用timeout参数,也可以全局使用$.ajaxSetup函数)
-
PHP,通过在PHP.ini 中设置max_execution_time
-
您的web服务器(Apache和IIS不同。例如,在IIS中,如果您通过FastCGI运行PHP,则必须在FastCGI设置中设置空闲超时、请求超时和活动超时)
-
可能是你的浏览器本身,尽管在过去这对我来说不是必要的
如果你在所有这些地方都设置了超时,它应该会起作用。对我来说,我和你一样完成了所有其他步骤,但直到我在FastCGI设置中设置了"活动超时"设置,问题才得到解决。