【发布时间】:2016-06-08 19:06:52
【问题描述】:
我需要关于单身课程的帮助。我正在创建一个 wordpress 插件,并且需要来自服务器的实时通知。为此,我使用了 AJAX 长轮询,我的代码如下所示。
这是一个 php 代码,用于服务 AJAX 请求和 LOG 类,它是单例的,从项目中的许多不同地方调用
if (isset($_GET['log']) && $_GET['log'] == 'true')
{
$response = array();
$response['msg'] = SI_log::get_instance()->get_message();
$response['type'] = 'something';
echo json_encode($response);
}
class SI_log{
private $log_messages = array();
private static $instance = NULL;
private $log_file;
public static function get_instance()
{
if (static::$instance === NULL) {
static::$instance = new static();
}
return static::$instance;
}
public function add_message( $message, $type )
{
array_push($this -> log_messages, $message);
}
public function get_message()
{
return end($this->log_messages);
}}?>
这是用于检索通知的 javascript,它是 wordpress 中管理部分的一部分。
<script type="text/javascript" charset="utf-8">
function waitForMsg(){
setTimeout(waitForMsg,5000);
document.getElementById("alerts").childNodes = new Array();
var request = new XMLHttpRequest();
request.open('GET', '<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true'?>', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
alert(resp);
var json = eval('('+resp+ ')');
document.getElementById("alerts").innerHTML= json['type'] +"<hr>";
if (json['type'] == 'WARNING'){
var html_element = '<div class="alert-message warning" id = "alert_warning"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'INFO'){
var html_element = '<div class="alert-message info" id = "alert_info"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'ERROR'){
var html_element = '<div class="alert-message errorr" id = "alert_error"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
document.getElementById("alerts") . innerHTML= html_element;
}else{
alert('<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true' ?>');
}
};
request.onerror = function() {
// There was a connection error of some sort
alert("request isnt good");
};
request.send();
}
window.onload = function (){
if (document.readyState != 'loading'){
waitForMsg();
} else {
document.addEventListener('DOMContentLoaded', waitForMsg);
}
}
</script>
这是如何从另一个类调用单例类以进行通知输入
SI_log::get_instance()->add_message("action triggered", 'INFO');
我认为问题是 SI_log 类中的单例模式实现,因此不仅有该类的一个实例,而且还有更多实例,当我尝试检索通知时,即。当我触发某些操作时,通知不会存储在同一个对象中。我使用了警报(resp);在 cilent 页面中显示响应和响应看起来像这样
{
"msg":false,
"type":"something"
}
在log.php中可以看到type值没问题,不是通讯问题。谁能帮帮我?
注意:我必须使用 Javascript 因为版本控制问题所以不要问我为什么不使用 JQuery
【问题讨论】:
-
我认为您误解了 PHP 的工作原理。单例在不同的请求中并不是唯一的。
-
你是说每个请求都实例化一个对象,而不是在该类之外?
-
他想说什么 google php "persistance" ,它会给你一些想法。根据您上面的代码,除了您现在得到的响应之外,没有任何代码可以检索任何内容。任何先前的连接都已关闭,因为已给出响应(再次基于给出的信息......你没有提到套接字/等 - 例如谷歌棘轮)。但对于 vanilla js 来说,这是一个不错的努力和 +1!
标签: javascript php ajax wordpress long-polling