阅读使用websocket和JQuery发送的JSON

时间:2016-12-10 16:12:30

标签: jquery json websocket

我试图通过JSON对象和websocket连接将一些信息推送到客户端。 JSON对象被正确发送,因为我已经使用JSON Web应用程序检查了它并且很好。

收到后,这是jquery-client代码;

$(document).ready(function(){

    var WEBSOCKET_ROUTE = "/ws";

    if(window.location.protocol == "http:"){
        //localhost
        var ws = new WebSocket("ws://" + window.location.host + WEBSOCKET_ROUTE);
        }
    else if(window.location.protocol == "https:"){
        //Dataplicity
        var ws = new WebSocket("wss://" + window.location.host + WEBSOCKET_ROUTE);
        }

    ws.onopen = function(evt) {
        $("#ws-status").html("Connected");
        };

    ws.onmessage = function(evt) {
    var json = JSON.parse(evt.data);
    $("#dia").html(json);
        };

    ws.onclose = function(evt) {
        $("#ws-status").html("Disconnected");
        };

$("#manual_on").click(function(x){
            var msg = {
    type: 'manual',
        text: $('#manual_on').val(),
    };
     ws.send(JSON.stringify(msg));
    $('#manual_on').val()= "";
        });

$("#manual_off").click(function(x){
         var msg = {
    type: 'manual',
        text: $('#manual_off').val(),
    };
     ws.send(JSON.stringify(msg));
    $('#manual_off').val() = "";
        });

$("#apertura").click(function(x){
         var msg = {
    type: 'programacion',
        hora: $('#hora').val(),
    minutos: $('#minutos').val(),
    tiempo: $('#tiempo').val(),
    lunes: $('#lu').prop('checked'),
    martes: $('#ma').prop('checked'),
    miercoles: $('#mi').prop('checked'),
    jueves: $('#ju').prop('checked'),
    viernes:$('#vi').prop('checked'),
    sabado: $('#sa').prop('checked'),
    domingo: $('#do').prop('checked'),
    };
     ws.send(JSON.stringify(msg));
        });
  });

这也是服务器端的python / tornado代码:

    #! /usr/bin/python

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
from tornado.ioloop import PeriodicCallback
import socket
import os.path
import json
import time

#Tornado Folder Paths
settings = dict(
    template_path = os.path.join(os.path.dirname(__file__), "templates"),
    static_path = os.path.join(os.path.dirname(__file__), "static")
    )


class MainHandler(tornado.web.RequestHandler):
  def get(self):
    print "[HTTP](MainHandler) User Connected."
    self.render("index.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
    self.callback = PeriodicCallback(self.send_msg, 120)
        self.callback.start()
        print 'new connection'

    def on_message(self, message):      
    data = json.loads(message)

    if data['type'] == 'programacion':

        hora=int(data['hora'])
        minuto=int(data['minutos'])
        tiempo=int(data['tiempo'])
        l=int(data['lunes'])
        m=int(data['martes'])
        x=int(data['miercoles'])
        j=int(data['jueves'])
        v=int(data['viernes'])
        s=int(data['sabado'])
        d=int(data['domingo'])
        global daylist
            daylist = []
            n=-1
            for i in (l, m, x, j, v, s, d):
             n=n+1
             if i==1:
                  daylist.append(n)
        print(time.time())

    elif data['type'] == 'manual': 
          print('manual')



    def on_close(self):
        print 'connection closed'

    def send_msg(self):
      timing=time.strftime("%H:%M:%S")
      timing2={'tiempo':timing}
      print json.dumps(timing2)
      self.write_message(json.dumps(timing2))

#sched.add_cron_job(job_function, month='6-8,11-12', day='3rd fri', hour='0-3')


application = tornado.web.Application([
    (r'/', MainHandler),
    (r'/ws', WSHandler),
   ], **settings)



if __name__ == "__main__":

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    myIP = socket.gethostbyname(socket.gethostname())
    print '*** Websocket Server Started at %s***' % myIP
    tornado.ioloop.IOLoop.instance().start()

除非我尝试在客户端读取JSON并将其放在html中,否则一切正常。我一直在这个论坛和互联网上看,但没有找到任何东西。你能帮我个忙吗?

感谢。

1 个答案:

答案 0 :(得分:0)

事实证明,实施没有任何问题,只是关于如何在html中编写响应

$("#dia").text(json.tiempo)