1 回答

TA貢獻1886條經驗 獲得超2個贊
您必須將 PHP 中的值回顯到 Javascript。但請注意,您需要首先驗證這些值。
像這樣的東西應該有效:
<?php
// get values from $_POST or default to empty string
$mac = $_POST['mac'] ?? '';
$ip = $_POST['ip'] ?? '';
?>
<button onclick="connect()" type="button" class="btn btn-info">CONNECT</button>
<script type="text/javascript">
function connect() {
// pass values as string to javascript variables
var mac = "<?php echo $mac; ?>";
var ip = "<?php echo $ip; ?>";
// mac and ip adresses provided
if (mac && ip) {
$("#login").modal();
}
// mac or ip adresses missing
else {
$("#error").modal();
}
}
</script>
有幾點需要注意:
這是不安全的,因為 POST 傳遞的值可能會被篡改。根據經驗,不要相信客戶提供的任何內容。
<?php echo ... ?>將“打印”文檔中的值。如果您在瀏覽器中檢查代碼,您將看到類似以下內容的內容:
var mac = "mac-address-passed-as-POST";
var ip = "123.456.78.90";
您可以echo使用簡寫語法來簡化語句:
var mac = "<?= $mac ?>";
var ip = "<?= $ip?>";
為了更好地驗證變量中獲得的值$_POST,您可以在 PHP 部分添加正則表達式檢查。就像是:
<?php
// default values
$mac = '';
$ip = '';
// validate mac address
if (isset($_POST['mac']) && preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $_POST['mac'])) {
$mac = $_POST['mac'];
}
// validate ip address
if (isset($_POST['ip']) && preg_match('/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/', $_POST['ip'])) {
$ip = $_POST['ip'];
}
?>
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報