我开始学习 strophe 库的使用,当我使用 addHandler 解析响应时,它似乎只读取 xml 响应的第一个节点,所以当我收到这样的 xml 时:
<body xmlns='http://jabber.org/protocol/httpbind'>
<presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
<status/>
</presence>
<presence xmlns='jabber:client' from='test@localhost' to='test2@localhost' xml:lang='en'>
<status />
</presence>
<iq xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='result'>
<query xmlns='jabber:iq:roster'>
<item subscription='both' name='test' jid='test@localhost'>
<group>test group</group>
</item>
</query>
</iq>
</body>
像这样使用处理程序 testHandler :
connection.addHandler(testHandler,null,"presence");
function testHandler(stanza){
console.log(stanza);
}
它只记录:
<presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
<status/>
</presence>
我错过了什么?这是正确的行为吗?我应该添加更多处理程序来获取其他节吗? 感谢提前
最佳答案
似乎是当函数 addHandler 被调用时,堆栈(包含所有要调用的处理程序的数组)在执行处理程序时被清空。所以当匹配handler条件的节点被调用时,栈被清空,其他节点就找不到了,所以你必须重新设置handler,或者像这样添加你希望被调用的handler:
connection.addHandler(testHandler,null,"presence");
connection.addHandler(testHandler,null,"presence");
connection.addHandler(testHandler,null,"presence");
或:
connection.addHandler(testHandler,null,"presence");
function testHandler(stanza){
console.log(stanza);
connection.addHandler(testHandler,null,"presence");
}
可能不是最好的解决方案,但我会一直使用,直到有人给我更好的解决方案为止,无论如何我都会发布此解决方法以提示我正在处理的代码流程。
编辑
阅读 http://code.stanziq.com/strophe/strophejs/doc/1.0.1/files/core-js.html#Strophe.Connection.addHandler 中的文档我发现这一行:
如果要再次调用处理程序,则应返回 true;返回 false 将在返回后删除处理程序。
因此只需添加一行即可修复:
connection.addHandler(testHandler,null,"presence");
function testHandler(stanza){
console.log(stanza);
return true;
}
关于javascript - Strophe.addHandler 只从响应中读取第一个节点是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2912530/