【问题标题】:Pass a socket io connection to an ajax success function将套接字 io 连接传递给 ajax 成功函数
【发布时间】:2016-08-26 00:38:05
【问题描述】:

我正在尝试在 ajax 成功函数中访问套接字 io 连接。

    // 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);
            });
        }
    });

我该怎么做?如果我在成功函数中声明连接,它可以正常工作

【问题讨论】:

    标签: jquery ajax socket.io


    【解决方案1】:

    您显示的内容看起来很混乱。 connect 事件可能在 ajax 调用完成之前已经发生,所以你会完全错过它。

    如果有正当理由不想在套接字连接之前将 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);
        });
    });
    

    【讨论】:

    • @Brian - 我已更新我的答案以匹配您的编辑。下一次,请告诉那些回复有针对性评论的人,您编辑了您的问题以解决他们指出的问题。否则,我们永远不会知道您进行了编辑。
    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2015-08-01
    • 2019-09-04
    相关资源
    最近更新 更多