无法在 cfwebsocket JS 函数发布时获取额外的参数值



我正在尝试使用 cfwebsocket 创建客户端到客户端聊天应用程序。我引用了土坯示例。在该示例中,我们将一个额外的参数传递给发布函数。所以我将接收器 id 传递给了发布函数,但无法在msgHandler函数中获取该值。

<cfoutput>
    <cfif !structkeyexists(session,'userName')>
        <cflocation url="index.cfm?msg=Please login first" addtoken="false">
    </cfif>
    <cfdump var="i am chat.cfm" />
    <a href="logout.cfm" style="float:right">Logout</a>
    <cfwebsocket name="myworld" onMessage="msgHandler" onOpen="openHandler"/>
    <script>
        var msgHandler = function(message){
            // Get data from the recieved message token
            var data = message.data;
            console.log(message.data.to);
            if(data){
                // If data is present write it to the div
                var txt=document.getElementById("myDiv");
                txt.innerHTML+= data + "<br>";
            }
        }
        var sayHello = function(){
            uname = document.getElementById("username").value;
            receiver = document.getElementById("selectUser").value;
            //var myData = {publishedBy: ''+uname, receiver:''+receiver}
            // Calling authenticate from client side. Calling this
            //function will invoke onWSAuthenticate from Application.cfc
            myworld.authenticate(uname,"password");
            myworld.subscribe("chat");
            // Client says Hello World
            myworld.publish("chat","Hello World! WebSocket is here !!",{to:receiver});
        }
        var openHandler = function(){
            // do nothing
        }
    </script>
    <input type="hidden" name="userName" id="username" value="#session.userName#">
    <input  id="hello" type="button" value="Say Hello!" onclick="sayHello();">
    <div id="myDiv"></div>
    <cfset users = Application.usersDAO.read()>
    <select name="user" id="selectUser">
        <option value="0">Select User</option>
        <cfloop query="users">
            <option value="#id#">#username#</option>
        </cfloop>
    </select>   
</cfoutput>

你应该像 json 对象一样传递你的消息和额外的参数。

var sayHello = function()
		{
			uname = document.getElementById("username").value;
			userID = document.getElementById("userID").value;
			receiverID = document.getElementById("ToUser").value;
			receiverName = document.getElementById("ToUserName").value;
			// Calling authenticate from client side. Calling this function will invoke onWSAuthenticate from Application.cfc
			myworld.authenticate(uname,"password");
			// Client says Hello World
			// console.log($('#input').val())
			msg = {'username': uname, 'userID' : userID, 'chat': $('#input').val().trim(), 'to':receiverID, 'receiverName' : receiverName };
			myworld.publish("world",msg);
			$('#input').val('');
		}

在msgHandler函数中,您将获得 message.data.to 和message.data.userId。您将在 msg处理程序内的会话作用域中存储用户 ID,您将比较会话用户 ID 和 message.data.to。如果两者相同,您将在聊天窗口中显示您的消息。

相关内容

  • 没有找到相关文章

最新更新