Failed to load resource: Request timed out on Safari

时间:2015-06-30 13:53:07

标签: jquery ajax web safari timeout

We have a web application working correctly for over a year now on most browsers. Recently we discovered it is not working that well on Safari.

A lot of actions end up with the following error : Failed to load resource: Request timed out. Funny thing is the action is actually performed correctly after that (most of the time).

When looking into the error, it seems to happen when there is an ajax request.

First I tried to change the ajax timeout setting by doing the following :

 $.ajax({
      "type"      : methode,
      "dataType"  : "json",
      "url"       : url,
      "async"     : async,
      "data"      : donneesEnvoyees,
      "timeout"   : 60000
 })

That didn't change anything at all, error is actually showing up after about 10 seconds which is less than the timeout defined.

After reading a bit on the internet, I saw some answer about specifying no-cache so that safari doesn't keep the post parameters in cache. I cannot say I fully understand that, but I still tried the following way :

$.ajax({
     "type"      : methode,
     "headers"   : { "cache-control": "no-cache" }, <-- added this line
     "dataType"  : "json",
     "url"       : url,
     "async"     : async,
     "data"      : donneesEnvoyees,
     "timeout"   : 60000
 })

As you can guess, I still get the same error.

Do you have any idea of what is happening? Why is this error happening only on Safari and not other browsers? How to fix it?

3 个答案:

答案 0 :(得分:5)

在ajax设置上设置async: true。它将使浏览器保持连接,并在收到响应后关闭。

答案 1 :(得分:2)

我遇到了同样的问题。通过将CORS标头和响应状态代码添加为 200

来修复
 res.header('Access-Control-Allow-Origin', '*');
 res.status(200);

如何&amp;为什么

通过阅读jQuery的源代码深入挖掘错误后,我意识到真正的问题是jQuery + Safari中的XMLHttpRequest使用http状态代码0调用 onError 。所以我添加了CORS标头并给它一个200状态代码来解决问题。

答案 2 :(得分:0)

如果您从ajax页面返回的内容不是dataType : "json"字符串,则从代码中删除JSON,我认为您的问题将得到解决。我注意到,如果提供了$.ajax()并且返回数据不属于dataType : "json"类型,则JSON不会转到成功函数。

<强> PS
有一些事情,比如AJAX设置关键字type, dataType, url等不应该是双引号。尽管代码即使按照当前的方式工作,但正确的方法是我提到的。

$.ajax({
      type      : methode,
      dataType  : "json",
      url       : url,
      async     : async,
      data      : donneesEnvoyees,
      timeout   : 60000,
      success   : function(data){
                alert('success');
      }
});

我认为您已经使用此ajax调用添加了success函数,您可以根据该结果使用不同的操作。