我有客户页面和 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/