繁体   English   中英

Socket.io数据为HTML文本

[英]Socket.io data to HTML text

我从在某些事件中触发的socket.io url获取这样的数据记录在控制台中。 现在我要做的就是从中获取特定数据,例如数量。

我已经尝试了很多方法来获取金额值和其他任何值,但是似乎没有任何效果。

这是我在.php文件中使用的唯一代码。

 <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js' type='text/javascript'></script> <script> const socketToken = 'mytokenishere'; //Socket token from /socket/token end point //Connect to socket const streamlabs = io(`https://sockets.streamlabs.com?token=${socketToken}`); //Perform Action on event streamlabs.on('event', (eventData) => { if (!eventData.for || eventData.for === 'streamlabs' && eventData.type === 'donation') { //code to handle donation events console.log(eventData.message); } if (eventData.for === 'twitch_account') { switch(eventData.type) { case 'follow': console.log(eventData.message); break; case 'subscription': //code to handle subscription events console.log(eventData.message); break; default: //default case console.log(eventData.message); } } }); </script> 

我试着做为document.write(eventData.message); 但这返回[object Object]
我也尝试了document.write(["0"].amount); 返回undefined

我非常感谢所有答复,如果您知道任何解决方案,请提前感谢!

编辑: document.write(JSON.stringify(eventData.message)); 给我

[{
    "isTest":true,
    "formatted_amount":"$87.00",
    "amount":87,
    "message":"This is a test donation for $87.00.",
    "currency":"USD",
    "from":"John",
    "from_user_id":1,
    "_id":"c3135e2c8011e545091f020f8378***"
}] 

看起来它是数组中的一个对象,我需要弄清楚如何制作它,因此它只是一个对象。

document.write(eventData.message[0].from); document.write(eventData.message[0].formatted_amount);
结果:约翰$ 87.00

所以这很简单..谢谢!

eventData.message[0]应该为您提供所需的基础对象。

您有一个要发送的对象数组,因此您需要通过访问索引0提取该数组的第一个元素。

例如eventData.message[0].amount应该为48

编辑:我在您陈述的地方看到了您的编辑

看起来它是数组中的一个对象,我需要弄清楚如何制作它,因此它只是一个对象。

只需创建一个新对象即可为该名称添加别名。

var data = eventData.message[0];
console.log(data.amount);

通过索引号访问数组项很简单。 例如:

console.log(eventData.message[0]) // log first item of eventdata's message

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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