这里使用的是websocket脚本。我想将按钮中的'message'值传递给webapp.js。但是我在每次点击按钮时只得到一个相同的值。
Javascript部分
</script><script src="webapp.js"></script>
数据库连接
<?php
//open the database
$db = new PDO('sqlite:server.db');
$result = $db->query('SELECT Room_Name,Id FROM FavoritesDetails
WHERE Room_Name="Bed Room" AND Id != "" ');
?>
Php Code
<form id="message-form" action="#" method="post">
<section id="mainroom" class="parallax fullscreen" style="background: url('images/roomm.jpg')">
<div class="container container-fullscreen text-light text-center">
<div class="text-middle">
<?php
foreach($result as $row)
{ ?>
<button class="button button1" type="submit" id="message" value="<?php echo $row['Id']; ?>" onclick="myFunction(this)"><?php echo $row['Id']; ?></button>
<?php
}
?>
</div>
</div>
</form>
webapp.js
window.onload = function() {
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
// Create a new WebSocket.
var socket = new WebSocket('ws://127.0.0.1:9300');
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.URL;
socketStatus.className = 'open';
};
// Handle messages sent by the server.
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:
</span>' +
message + '</li>';
};
// Show a disconnected message when the WebSocket is closed.
socket.onclose = function(event) {
socketStatus.innerHTML = 'Disconnected from WebSocket.';
socketStatus.className = 'closed';
};
// Send a message when the form is submitted.
form.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' +
message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
};