第一次尝试使用Pusher,并且..不确定其是否有效。
当页面加载时,我在console.log
代码中放入的js
语句触发,表明Pusher
对象处于以下状态:Initialized > Connecting > Connected
但是,我将一个简单的ajax调用绑定到connected
事件,希望只发送然后接收Pusher.connection.socked_id
。一旦进入了ajax调用的success
函数,我只想显示返回的socket_id
。
同样,我的所有显示都显示在控制台中,并使该应用程序似乎正在运行,包括Successful Ajax Call
回调中的success
消息,但是我没有收到任何数据。 data
对象显示为undefined
,如果我在HandleEvent
服务器端方法中设置了断点,它将永远不会触发。
知道我在做什么错吗?
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);
});
由于响应返回json,请尝试以下命令。
查看完整回复
alert(JSON.stringify(data));
仅查看消息
alert( data.message);