我正尝试转换MQTT字符串并将其添加到mysql中,我设法转换了这些字符串并使其在chrome控制台中正确显示,但是我缺少javascript和PHP之间的位来传递数据。 / p>
我已经尝试过本网站上其他问题中概述的某些内容,但是我可以使它们正常工作,我尝试使用AJAX,但又无法使其正常工作,这是我哪里出了问题或我缺少什么?
以下所有代码均在服务器端运行。
var hostname = "127.0.0.1";
var port = 1884;
// Create a client instance
var client = new Paho.MQTT.Client(hostname, Number(port), "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
onSuccess: onConnect
});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("test");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
var raw = message.payloadString;
message.length = raw.length;
message.raw = raw;
var data = {};
data.major = raw.slice(-10,-4);
data.mac = raw.substring(5,17);
data.hostname = raw.substring(18,30);
data.minor = raw.slice(-8,-4);
var str = data.hostname;
var location = str.replace(`C129E53D0F45`, `PINK`)
.replace(`FD139CD46385`, `DARKORANGE`)
.replace(`EB72F2609789`, `DEEPSKYBLUE`)
.replace(`DBECEE45AE6F`, `RED`)
.replace(`E47D6D760A7F`, `WHITE`)
.replace(`C3D7EDB7EF28`, `WHITE`)
.replace(`E3A3BD636EA3`, `GREEN`)
.replace(`D6F579FC35C9`, `YELLOW`);
var beacon = parseInt(data.minor ,16);
var topic2 = ('[value="'+location+','+beacon+', '+data.mac+'"]')
console.log("Message arrived: topic=" + message.destinationName + ", message=" + topic2);
}
</script>
<?php
$servername = "127.0.0.1";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test.track (`location`,`beacon`, `mac`) VALUES ('+location+','+beacon+', '+data.mac+')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>