Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 将套接字io连接传递给ajax成功函数_Jquery_Ajax_Socket.io - Fatal编程技术网

Jquery 将套接字io连接传递给ajax成功函数

Jquery 将套接字io连接传递给ajax成功函数,jquery,ajax,socket.io,Jquery,Ajax,Socket.io,我试图在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:

我试图在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);
            });
        }
    });

我该怎么做?如果我在success函数中声明了连接,它工作正常

您显示的内容看起来很混乱。在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);
    });
});

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