简体   繁体   English

超时无法在ajax post请求中工作

[英]Timeout not working in ajax post request

I am not able to make ajax error callback function of after 3 seconds. 我无法在3秒后制作ajax错误回调函数。 I tried with timeout, but it will not switch to error callback after specified time! 我尝试了超时,但在指定的时间后它不会切换到错误回调! I am not able to get the alert Got timeout . 我无法获得警报Got timeout

When I referred similar questions in this site with similar problems it didn't helped out. 当我在这个网站上提到类似问题的类似问题时,它没有帮助。 They all use ajax GET type. 它们都使用ajax GET类型。 I am using jquery 1.10.1 library. 我正在使用jquery 1.10.1库。

script : 脚本:

$.ajax({
  type: 'POST',
  timeout: 3000,
  url : "http://mydomain/Services.asmx/Best_Scores",
  dataType: "text",
  async:false,
  crossDomain:true,
  data: "strJsonRequest="+scoredata,
  success: function (data) {
    // Success code ...
  },
  error: function (data, textStatus, errorThrown) {
    if(textStatus == "timeout") {
      alert("Got timeout");
    }
  }
});

Any solution ? 有解决方案吗

Fix : 修复:

Change async : false to async: true async : false更改为async: true

Reason : 原因:

A synchronous AJAX call blocks until the request has been finished. 同步AJAX调用将阻塞,直到请求完成。 Implementing a timeout is not possible for technical reasons, because the AJAX call would have to be executed later. 由于技术原因,无法实现超时,因为以后必须执行AJAX调用。

If an AJAX call is executed later, the function somehow has to implement a blocking feature, to stop the code from running further after the AJAX call, and execute it again after a timeout - not possible. 如果稍后执行AJAX调用,该函数必须以某种方式实现阻塞功能,以阻止代码在AJAX调用后进​​一步运行,并在超时后再次执行 - 不可能。

Today, (in 2019) I still have this problem. 今天(2019年),我仍然有这个问题。

I have an ajax call too long (depending from Date Start-> Date End) php script. 我有一个ajax调用太长时间(取决于Date Start-> Date End)php脚本。

and after some minutes I get error 500, async: true don't help. 几分钟后我得到错误500,async:true没有帮助。

The call is: 电话是:

$.ajax({
    type: "GET",
    dataType: 'json',
    url: 'mymscript.php',
    contentType:'application/json;charset=UTF-8;',
    data: $('[name="myForm"]').serialize(),
    async:true,
    timeout:0,
success: function(response){
...

I resolved using: side PHP: 我决定使用:side PHP:

set_time_limit(0);
ignore_user_abort(true);

at begin of script. 在脚本开始。

echo ' ';
flush();
ob_flush();

in the middle of script (for example in main loop every day). 在脚本中间(例如每天在主循环中)。 This help to let client to don't disconnect (I think that is the main problem). 这有助于让客户端不要断开连接(我认为这是主要问题)。

Using this I continuosly write spaces befor the final json. 使用这个我继续为最终的json写空格。 Fortunately jquery trim spaces before to parse the json and, in the end, the json is valid. 幸运的是,jquery在解析json之前修剪了空格,最后,json是有效的。

So I can catch response object to know if script is ended with errors or warnings. 所以我可以捕获响应对象,以了解脚本是否以错误或警告结束。

I Hope this help somebody. 我希望这能帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM