Jquery封装: WebSocket插件

 1   $(function() {
 2     var websocket = null;
 3    //浏览器是否支持websocket
 4     if ("WebSocket" in window) {
 5         try {
 6             websocket = new WebSocket($("#socketUrl").val());
 7             websocket.onopen = function(data) {
 8                 // console.log("connect success ");
 9             };
10 
11             websocket.onmessage = function(data) {
12                 if (!isJsonFormat(data.data)) {
13                     // console.log("onmessage : " + data.data);
14                 } else {
15                     var dataJson = JSON.parse(data.data).files;
16                     if (null != dataJson) {
17                         var imgId = $('.waite-for-ws').attr('imgId');
18                         for ( var key in dataJson) {
19                             var path = dataJson[key].filePath;
20                             
21                             $('#' + imgId).attr('src', ctx + "/wsla/download?filePath=" + path);
22                             $('#' + imgId).attr('path', path);
23                             $('#' + imgId).show();
24                             
25                             $('.waite-for-ws').parent().siblings('input[type=hidden]').val(path);
26                             
27                         }
28 
29                         var index = imgId.lastIndexOf("-");
30                         var selector = '#' + imgId.substring(0, index) + '-tips';
31                         $(selector).hide();
32                         $(selector).css('display', 'none');
33                         
34                         $('.waite-for-ws').removeClass('waite-for-ws');
35                         // $('#uploadSuccessDiv').show();
36                         $("#div-show").hide();
37                         
38                         if (imgId == 'id-01-img' || imgId == 'id-02-img') {
39                             sfzjzpTip();
40                         } else if (imgId == 'id-03-img') {
41                             lszjpTip();
42                         } else if (imgId == 'id-04-img') {
43                             yyzzjpTip();
44                         }
45 
46                     } else {
47                         $("#div-show").show();
48                     }
49                 }
50             };
51 
52             websocket.onerror = function(e) {
53                 // console.log('connect error ');
54             };
55 
56             websocket.onclose = function(data) {
57             };
58 
59             window.onbeforeunload = function() {
60                 websocket.close();
61             }
62 
63         } catch (error) {
64             // console.log('connect error ');
65         }
66 
67     } else {
68         // console.log("Websockets not supported");
69     }
70 
71     $('.close').click(function() {
72         if (websocket != null) {
73             websocket.close();
74         }
75     });
76 
77 });