简体   繁体   中英

Pusher Ajax call doesn't seem to be working

Trying to use Pusher for the first time and.. not sure if it is working or not.

When the page loads, the console.log statements I've put in the js code fire, showing that the Pusher object goes through the following states: Initialized > Connecting > Connected

However, I've bound a simple ajax call to the connected event hoping to just send, and then receive, the Pusher.connection.socked_id . Once in the success function of the ajax call I just want to display the returned socket_id .

Again, all my displays show up in the console and make the app appear to be working, including the Successful Ajax Call message in the success callback, however I am not receiving any data. The data object displays as undefined , and if I set a breakpoint in the HandleEvent server-side method it never fires.

Any idea what I'm doing wrong?

C#

    [HttpPost]
    public void HandleEvent(string socket_id)
    {
        var pusher = new Pusher(PusherConfig.APP_ID(), PusherConfig.KEY(), PusherConfig.SECRET());
        var result = pusher.Trigger("test_channel", "my_event", new { message = socket_id });
    }

Pusher App

$(document).ready(function () {   
Pusher.log = function(message) {
    if (window.console && window.console.log) {
       console.log(message);
    }
};

var pusher = new Pusher(key);
var socketId = null;
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function (data) {
    alert(data.message);
});
pusher.connection.bind('initialized', function (data) {
    console.log('initialized');
});
pusher.connection.bind('connecting', function (data) {
    console.log('connecting');
});
pusher.connection.bind('connected', function (data) {
    console.log('connected');
    socketId = pusher.connection.socket_id;

    $.ajax({
        url: 'api/Values/HandleEvent',
        type: "POST",
        data: { socket_id: socketId },
        success: function(data) {
            console.log("Succesful Ajax Call");
            console.log("Data: " + data);
        },
        error: function(error) {
            console.log("Bad Ajax Call");
        }
    });
});
pusher.connection.bind('unavailable', function (data) {
    console.log('unavailable');
});
pusher.connection.bind('failed', function (data) {
    console.log('failed');
});
pusher.connection.bind('disconnected', function (data) {
    console.log('disconnected');
});
console.log("State: " + pusher.connection.state);

});

since response is returning in json, please try the following commands.

to view full response

alert(JSON.stringify(data));

to view the message only

alert( data.message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM