【问题标题】:Ajax call VERY SLOW with PHPAjax 使用 PHP 调用非常慢
【发布时间】:2013-12-14 11:48:06
【问题描述】:

我正在使用 Ajax 通过 Twitter Bootstrap 选项卡在 div 中加载另一个页面的内容,但是 ajax 加载页面的时间过长。
没有 Ajax 页面加载速度非常快!

在 ajax 调用中加载的页面:28.743376016617 毫秒
页面加载时没有 ajax:0.00022506713867188 ms

这是ajax调用的代码:

    $(function() {
    $("#MainTabs").tab();
    $("#MainTabs").bind("show", function(e) {
      var contentID  = $(e.target).attr("data-target");
      var contentURL = $(e.target).attr("href");

      if (typeof(contentURL) != 'undefined')

    $(contentID).html('<img src="<?php echo IMG_DIR; ?>loading/loading-large.gif" width="64" />').load(contentURL, function(){
        $("#MainTabs").tab();
    });
      else
    $(contentID).tab('show');
    });
    $('#MainTabs a:first').tab("show");
}); 

这是一个 PHP 代码:

<?php
$start = microtime(TRUE); // Start counting

ob_start();
session_start();

$temp = microtime(TRUE) - $start;
echo $temp;

exit;

/*
 * Here is the rest of the contents of the script, so I gave the 'exit' and even with the exit delay it that way!
*/

有谁知道发生了什么以及如何帮助我? PHP代码很简单,耗时太长!

谢谢!

【问题讨论】:

  • 即使它是同步的,通过单个请求测试它应该不会有太大的区别......当然不会有那么大的区别。
  • 这是你的真实密码吗?还有其他的包含吗?数据库连接和其他类似的东西?
  • 是否可能有其他请求同时运行?在这种情况下,可能是会话文件锁定阻止了通过 AJAX 请求的脚本。
  • @chumkiu 令人惊讶的是,这是我的实际代码!简单而且非常,但是非常慢!
  • 如果我在没有 Ajax 的情况下直接在浏览器中输入脚本,它的加载速度非常快。

标签: javascript php ajax jquery


【解决方案1】:

请使用 .ajax() 调用而不是 .load()。

试试这个:

$(contentID).html('<img src="<?php echo IMG_DIR; ?>loading/loading-large.gif" width="64" />');
$(contentID).ajax(
   url: contentURL, 
   type: "GET",//or POST
   success: function(data){
     $(contentID).html(data);
     console.log(data);//it will show the error log if any [optional]
   }
});

Check here for ajax call

【讨论】:

  • 您应该进一步扩展您的答案以赋予它更多的信息价值,尤其是关于“为什么”。这看起来应该是一个评论(至少对我来说)。
【解决方案2】:

您的 Ajax 是否从需要时间来生成 html 的后端加载 html?

如果没有 Ajax,您加载的数据更少,因此它的运行速度很快。

如果您加载不常见的数据,则通过异步脚本加载。页面加载后几秒钟后加载 ajax div。

  1. 如果加载时间过长,请取消 ajax 请求。

    $(document).ready(
    var xhr;
    
    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };
    
    var interval = setInterval(fn, 500);
    

    );

【讨论】:

    【解决方案3】:

    我有同样的问题,添加标题后:

    header("Content-Length: xxx")
    

    它的工作速度非常快。

    【讨论】:

    • 你能解释一下吗?你在哪里添加的,为什么它现在很快?
    • @Jagar - 我认为这是因为客户端正在等待更多响应数据,即使不会发送更多数据,这会导致延迟......当客户端知道总 Content-Length它不会再等待了,因为它知道它已经拥有了所有的数据……这个标头被放到输出数据的响应脚本中。
    猜你喜欢
    • 2016-05-11
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多