I am using PubNub to publish and subscribe messages. There is a technical requirement in which I have to add the PubNub Channel Name dynamically. The problem is, I cannot load my page again. All the work I am doing is through jQuery and interacting with my server using AJAX.

Is it possible to do so. If yes, then how.

Best, Abhinav Sharma

有帮助吗?

解决方案

Yes it is possible. First initialize your pubnub using PUBNUB.init() method if you don't use a div for your setup credentials. Then you can make an AJAX request to your server to obtain the channel name. After obtaining the channel name, just subscribe to it via the pubnub subscribe() call. You can subscribe to a PubNub channel at any time.

Assuming your server will respond to your request with text datatype:

var pubnub = PUBNUB.init({'publish_key':'demo','subscribe_key':'demo'});
pubnub.ready();
$.ajax({
    url :'http://example.com/getchannel',
    type :'GET',
    dataType :'text',
    success : function(data) {
        pubnub.subscribe({
            channel : data,
            message : function(m) { console.log('new message received: ',m);
        });
    }        
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top