【发布时间】:2017-07-23 01:52:18
【问题描述】:
我使用 while 循环创建了一些数据(从数据库生成)。每组数据都带有某种形式的 id,并在其中添加相应的按钮。现在,当我单击一个按钮时,我想将与此按钮相关的数据的 id(单个 php 变量)传递给一个弹出的模式窗口(具有一个表单),并使其成为输入字段的值.到目前为止,这是我的代码:
数据库中的数据:
<?php while ($data = mysqli_fetch_assoc($data_set)) { ?>
<div class="w3-section w3-row w3-card-2">
<div class="w3-half">
<div class="apartment-image w3-card-4">
<header class="w3-container">
<h4><?php echo $data['data_name']; ?></h4>
</header>
<div class="w3-container">
<img src="<?php echo "images/".$data['Image1']; ?>" class="w3-image" alt="<?php echo $data['dataimgname']; ?>">
</div>
<footer class="w3-contanier w3-border-top">
<div class="w3-border-right">
<button class="w3-btn w3-btn-block" type="button" name="btnBook" id="modalOpener" onclick="document.getElementById('book').style.display='block';">
Book or Request Tour
</button>
</div>
模态:
<div id="book" class="w3-modal">
<div class="w3-modal-content">
<header class="w3-container">
<span onclick="document.getElementById('book').style.display='none'" class="w3-closebtn">
×
</span>
<h2>Book or Request Tour</h2>
</header>
<div class="w3-container">
<form class="w3-form" action="bookntour-handler.php" method="post">
<div class="w3-group">
<label class="w3-label" for="fullname">Full Name:</label>
<input class="w3-input" type="text" name="fullname" value="">
</div>
<label class="w3-label" for="email">E-mail:</label>
<input class="w3-input" type="email" name="email" value="">
<label class="w3-label" for="telephone">Telephone:</label>
<input class="w3-input" type="text" name="telephone" value="">
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
<div class="w3-group">
<input class="w3-btn" type="submit" name="btnSubmit" value="Submit">
</div>
</form>
</div>
<footer>
</footer>
</div>
就像我之前说的,我想传递与按钮关联的 id,但在我的代码中没有提到“id”,所以让我们使用吧。
<?php echo $data["data_name"]; ?>
当我打开模态窗口时,我希望将这个变量作为输入值:
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
到目前为止,我已经查看了几个选项,但其中大多数在我的情况下似乎是不必要的,或者我根本不理解它们。比如this 和this 和this。 This 似乎是一个可行的解决方案,但它需要我从我不想要的数据库(使用 AJAX)中再次获取整个数据。我只想要那个值。
我使用W3CSS 进行布局并创建模式。 jQuery/JavaScript 或 PHP(或两者)的解决方案将不胜感激。谢谢!
更新
所以,我设法解决了部分问题。我将此函数添加到我的外部 JavaScript 文件中:
function showModal() {
document.forms["bookntourForm"]["apartmentno"].value = document.getElementsByClassName("modalOpener")[0].getAttribute("value");
document.getElementById('book').style.display='block';
}
那么调用上述函数的按钮代码如下:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal()" value="<?php echo $data['data_name']; ?>">
Book or Request Tour
</button>
这带来了一个新问题。每当我打开模态时,模态上<input class="w3-input" type="text" name="dataname" value=""> 的值对于所有模态都是相同的,尽管在生成每个按钮时它们是不同的。
【问题讨论】:
-
虽然这样做可能会带来安全问题,但一种方法是将 ID 作为 GET 传递,然后让模态检查该 GET 是否有值
标签: javascript php jquery html