我想设计一个能够在更改开关状态或填写并提交表单等时在mqtt代理上发布消息的Web应用程序。我能够在节点上使用mqtt库发布消息。当使用javascript和jquery在html页面上更改时,我也能够检测到正常的开关状态。现在我想在这里从节点app调用mqtt发布函数。我该怎么做?
这是普通的html文件switch.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="switch.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="switch.js"></script>
</head>
<body>
<h2>Toggle Switch</h2>
<label class="switch" id = "switchLabel1">
<input type="checkbox" id = "switch1">
<div class="slider round"></div>
</label>
</body>
</html>
检测交换机状态switch.js
的javascript$( document ).ready(function() {
$('#switch1').attr('checked', true);
$('#switch1').click(function(){
if($(this).prop("checked") == true){
console.log("switch1 is checked.");
}
else if($(this).prop("checked") == false){
console.log("switch1 is unchecked.");
}
});
});
Nodejs app向mqtt index.js发布消息。使用npm安装MQTT库。
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.15.3')
client.on('connect', function () {
client.subscribe('mqtt_node_subscribe')
client.publish('mqtt_node_publish', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
})
我想要做的是在switch.js中调用client.publish(&#34;主题&#34;,&#34;消息&#34;)而不是console.log
当我这样做时,它说客户端没有定义,所以我尝试合并两个js和运行节点,它说$ not defined。我尝试在节点应用程序中包含jquery,它说窗口丢失了。所以我需要一个方法来使用节点来服务这个Web应用程序并按原样使用jquery等。
答案 0 :(得分:0)