weixin_33724046 2015-08-20 10:31 采纳率: 0%
浏览 28

用PHP发送服务器事件

I have a web app which sends some data from a js script to a php server which inserts it into a mysql database. I also need to notify all other clients that the data has been sent and send it to them.

I'm trying to use Server-Sent Events to do this but I'm having some trouble grasping the concept. Here's my code:

$(document).ready(function() {
    var source = new EventSource("../Server/insertMessage.php");
    if(typeof(EventSource) == "undefined") {
        alert("event source doesnt work");
    } else { alert("event source works"); }

    source.onmessage = function(event) {
        alert(event.data);
        // do stuff with event.data
    };
});

Elsewhere in my js script, I send an AJAX request to insertMessage.php with POST parameters as the data details. Does this trigger the server-side event? Here's my server side code:

insertMessage.php

if(isset(// check POST to see if the right request was sent)) {
    // insert data into database
    // ...
    // ...

    // Send the new data to listeners
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    // Create data array
    $dataArray = array("data" => $data, "moreData" => $moreData);
    // Encode JSON
    $callback = json_encode($dataArray);
    // Send it
    echo "data: $callback";
    flush();
}

While the "event source works" alert is sent, I never get the event.data alert, even though I am making the AJAX call to insertMessage.php. I may not completely understand Server-Sent Events yet. What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • H_MZ 2015-08-20 22:04
    关注

    The reason this isn't working is because when your JavaScript is creating the EventSource or is doing an HTTP GET. So your PHP code is not returning anything. You can't do POST requests with an EventSource.

    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答