javascript - 执行 imap_close 不工作

标签 javascript php jquery ajax imap

我有客户页面和 ajax 即时加载信息,了解他们是否向我们发送电子邮件。

代码如下所示:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'email';
$password = 'password';

$this->session->data['imap_inbox'] = $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

 foreach($customers as $customer){
     $emails = imap_search($inbox, 'FROM ' . $email);
     // Processing info
 }

但是一个页面上大约有 20-30 个客户,所以这个过程有时需要大约 10-20 秒才能显示,我无法优化这个过程。

但是当客户端尝试重新加载页面时,它仍在等待 imap_search 完成,因此在重新加载时可能需要 20 秒才能真正重新加载页面。

我尝试使用 beforeunload 函数中止 ajax 并关闭 imap 但这不起作用。

我的代码:

Ajax :

    $(window).bind('beforeunload',function(){
    imap_email.abort(); // the ajax is succesfully aborted(as showed in console), yet the page still takes considerable time to reload

    $.ajax({
        type: 'GET',
        url: 'getimapmails&kill=1',
        async:false
    }); // ajax call to the same function to call imap_close 

});

PHP:

if($this->request->get['kill'] == '1'){
            imap_close($this->session->data['imap_inbox']);
            unset($this->session->data['imap_inbox']);
            $kill == 1;
            exit;
        }

但即使 ajax 被中止并且 imap_close 被调用在持有 imap_open 的变量上,页面仍然需要 10-20 秒才能完成重新加载,所以我假设 imap 没有关闭。

如何关闭 imap 以便页面可以立即重新加载?

最佳答案

我建议通过创建一个导致中断的文件来杀死它:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'email';
$password = 'password';

$this->session->data['imap_inbox'] = $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

 foreach($customers as $customer){
      clearstatcache(); //Can't use the cached result.
     if(file_exists('/tmp/kill_imap.'.$this->session->id)) break;  //making the assumption that /tmp and session->id are set, but the idea is a temporary folder and a unique identifier to that session.
     $emails = imap_search($inbox, 'FROM ' . $email);
     // Processing info
 }
 if(file_exists('/tmp/kill_imap.'.$this->session->id)) unlink('/tmp/kill_imap.'.$this->session->id);

然后在退出 ajax 时,只需调用一个简单地创建该文件的 php 脚本。它会打破你的循环并删除文件。

关于javascript - 执行 imap_close 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919417/

相关文章:

javascript - 使用下拉列表显示/隐藏

javascript - 使用 Javascript/Jquery 将 Word 文件转换为 PDF

javascript - 子进程完成时的事件

javascript - 使用绑定(bind)强制原型(prototype)函数的上下文

php - 如何查明网站是在什么框架或什么语言上创建的?

php - 访问 $OPENSHIFT_DATA_DIR 上的上传文件

javascript - 然后在评估之后总是返回一个对象

javascript - Durandal SPA 与 typescript 有关的问题

php - PDO:MySQL 服务器已经消失,无法捕获异常

javascript - setInterval 函数返回未定义