【问题标题】:jQuery .load doesn't work whilst ajax query is in progressjQuery .load 在进行 ajax 查询时不起作用
【发布时间】:2017-03-13 17:45:57
【问题描述】:

我有一个 Web 应用程序,它使用 ajax 请求或 .load() 请求将不同的内容加载到同一个 div (.content) 中。

ajax 请求的简化版本是:

    $(document).on('click', '.button1', function() {
        $.ajax({
        type: "POST",
        url: "/path/to/file/ajax.php",
        data: {
            'param1': 'xyz',
            'param2': '123',    
        },
        timeout: 10000,
        dataType: "json",
        success: function(data) {
            if (data.status == 'Success') {
                $('.content').html(data.result);
            } else if (data.status == 'Error'){
                console.log('Something went wrong')
            }
        },
        error: function(x, status, error) {
            if (status === "timeout") { 
               console.log('Request Timed Out');
            } 
        },
        }); 
    });

在我的另一个按钮上:

    $(document).on('click', '.button2', function() {
          $('.content').load('/path/to/file/getContent.php?ref=foo');
    });

问题是,如果我单击按钮 1,然后在 ajax 请求仍在执行时单击按钮 2,则没有任何反应。 (即 getContent.php 似乎在 15-30 秒之间没有返回任何内容)

单击按钮 2 会立即返回结果,但一旦单击按钮 1 并处理 ajax 请求,它似乎会“停止”整个网络应用程序,直到它完成(或出错)。

(我也尝试过使用 abort() 方法取消 ajax 请求,但同样的问题仍然存在,即使中止成功)。

更新 请参阅下面的解决方案/答案

【问题讨论】:

  • 问题很可能不是前端,而是服务器。 PHP 有时会遇到使用相同会话变量等的多个请求的问题。
  • @adeneo 感谢您的回复 - 我从 ajax.php 和 getContent.php 中删除了 session_start() (它们可能是矫枉过正,因为它也在 main.php 页面中调用),这似乎已经修复问题!在发布更新之前会进行更多测试。

标签: javascript php jquery ajax session


【解决方案1】:

根据@adeneo 的提示,我对 session_start 和 ajax 调用进行了更多研究,这导致我写了这篇文章:

http://konrness.com/php5/how-to-prevent-blocking-php-requests/

问题绝对与 session_start 锁定会话文件有关,这会导致多个 ajax 请求出现后端问题。按照上面文章中的建议,我在我的 PHP 中使用了 session_write_close() 并且一切正常。

如果它对其他人有帮助,我实际上将我的代码从 session_start() 更改为:

    if (session_status() == PHP_SESSION_NONE) {
       session_start();
       session_write_close();
    }

这使得会话变量可读,但不再锁定会话文件导致 ajax 请求延迟。 (它还会检查以确保 session_start() 尚未被调用)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多