2016-08-26 47 views
0

我试图访问ajax成功函数内的套接字io连接。将套接字io连接传递给ajax成功函数

// Create socket connection 
    var socket = io.connect('http://localhost:81/'); 

    // Ajax request gets auth token 
    $.ajax({ 
     url: 'http://localhost:8000/foo', 
     xhrFields: { 
      withCredentials: true 
     }, 
     success: function (result, textStatus, jqXHR) { 
      socket.on('connect', function() { 
       $('#rows').html(result); 
       socket.emit('message', result); 
      }); 
     } 
    }); 

我该怎么做?如果我声明成功功能内的连接,它工作正常

回答

1

你显示什么看起来很困惑。在ajax调用完成之前,connect事件可能已经发生,因此您完全会错过它。

如果有一个合法的理由不想要插入的AJAX结果到DOM,直到套接字连接,那么你可以做这样的:

// Ajax request gets auth token 
// start ajax call, save promise 
var p = $.ajax({ 
    url: 'http://localhost:8000/foo', 
    xhrFields: { 
     withCredentials: true 
    } 
}); 

// Create socket connection 
var socket = io.connect('http://localhost:81/'); 
socket.on('connect', function() { 
    // when both socket is connected and ajax call is done, insert results into DOM 
    p.then(function(results) { 
     $('#rows').html(result); 
     socket.emit(result); 
    }); 
}); 
+0

@布赖恩 - 我已经更新了我的答案以匹配您的编辑。下一次,请告诉那些已经回复了有针对性评论的人,您已经编辑了您的问题,以解决他们指出的问题。否则,我们永远不知道你做了编辑。 – jfriend00

+0

好酷。它虽然工作。 – Brian

相关问题