我很困惑,如何從js獲取數據到php變量。在JS函數中,我在事件上頻繁獲取數據。問題是我想頻繁地獲取數據,因爲它是實時數據。包含數據到來時的數據。所以我必須連續得到的值。從js函數獲取php的值
<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="mqttws31.js" type="text/javascript"></script>
<script>
function myFunction(p1, p2) {
return p1 * p2;
};
var mqtt,payload;
var value = 10;
var reconnectTimeout = 2000;
function MQTTconnect() {
if (typeof path == "undefined") {
path = '/mqtt';
}
mqtt = new Paho.MQTT.Client(
'broker',
1883,
"/mqtt",
"a:" + "abcdef" + ":" + Date.now()
);
var options = {
timeout: 3,
useSSL: false,
cleanSession: true,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
options.userName = 'user';
options.password = 'password';
mqtt.connect(options);
}
function onConnect() {
document.writeln("connected");
// Connection succeeded; subscribe to our topic
mqtt.subscribe('iot-2/type/+/id/+/evt/evt1/fmt', {qos: 0});
//$('#topic').val('iot-2/type/" + "+" + "/id/" + "+" + "/evt/evt1/fmt');
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
//$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
payload = message.payloadString;
//document.writeln(payload);
//document.write("\n");
//$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
</script>
</head>
<body>
<?php
$db = '<script type="text/javascript">document.write(MQTTconnect());</script>';
$db1 = '<script type="text/javascript">document.write(payload);</script>';
echo $db;
echo $db1;
?>
</body>
</html>
我真的不認爲有任何其他可靠的辦法,而不是發送值使用最有可能的Ajax調用服務器。 –
@DavidPacker你可以在這種情況下建議如何使用ajax .. – vikky
我現在沒時間了,但是你真的不應該混合DOM操作和服務器端渲染。如果沒有人回答問題,我會在稍後發佈答案。 –