我想在点击一个button时在node.js服务器上触发一次server-sent-event

我想要做一个这样的过程:

  1. 用户selectcombobox菜单,然后单击“提交”button。

  2. node.js服务器上的路由器路由来自客户端的请求。

    路由器做了什么:

    1. 从客户端获取信息

    2. 查询数据库并获取数据。

    3. 用数据发送一个'draw_chart'事件stream到客户端html页面。
    4. 所以页面上的函数被使用来自服务器的数据触发。

所以我在这样的客户端html页面上创build了一个表单

chart.html:

<form action = "http://localhost:1337/draw_chart" method = "GET"> <select id = "xAxisList" name = "xAxisList"></select> <select id = "yAxisList" name = "yAxisList"></select> <input type = "submit" id = "create_chart">Click to Draw a Chart</input> </form> 

并使用express模块​​创build了一个路由器,以便在node.js服务器上路由来自客户端的请求。

server.js:

 function draw_chart_handler(req,res){ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); var x = req.body.xAxisList; // get the name of x-axis from the form var y = req.body.yAxisList; // get the name of y-axis from the form // the three lines below is using external modules. chart_generator.setX(x); chart_generator.setY(y); var d = chart_generator.generateChartData(); // get the data from the data base and manufacture the data for generating chart. var data = "event: draw_chart\n" + "data: "; data += JSON.stringify(d) + "\n\n"; res.write(data); res.end(); } app.get('/draw_chart',draw_chart_handler) 

他们完全分开工作….

事件不断发生,即使我从来没有点击button,

当我点击button,新的页​​面出现在页面上的'数据'

这是从服务器发送的方法'res.write(data);'….

我不想逃避原来的页面…. 🙁

我想我不了解事件stream….

我search了很多网站的node.js学习,但我找不到答案。

当点击一个button来传递客户端和服务器之间的数据而不逃避页面时,我怎么才能做一个服务器发送事件?