我正在使用php ajax传递并获取结果,但是javascript仅采用第一个循环值
这是我的代码:
<?php
$sql = 'SELECT * from booking_master
INNER JOIN *****
WHERE booking_master.user_id=:id';
$query = $conn->prepare($sql);
$query->bindParam(':id', $id);
$query->execute();
if($query->rowCount())
{
while($row11 = $query->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td> <?php echo $row11['user_name']; ?> </td>
<input type="hidden" name="userid" id="userid" value="<?php echo $row11['user_id']; ?>">
<input type="text" value="<?php echo $row11['plot_id']; ?>" name="plotid" id="plotid">
<td> <?php echo $row11['auto-book-id'];?></td>
<td> <?php echo $row11['plot_id'];?> </td>
<td> <?php echo $row11['plot_name'];?></td>
<td> <?php echo $row11['trans_date'];?></td>
<td> <a href="#" onclick="functscheme()" > Select Plot</a>
</tr>
<?php
}
}
?>
ajax代码:
function functscheme()
{
var userid=document.getElementById('userid').value;
var plotid=document.getElementById('plotid').value;
alert(plotid);
但是在该图中,它仅返回第一个值
答案 0 :(得分:0)
getElementById
仅返回具有该ID的第一个元素(因为ID仅用于一个元素)。尝试改用类。
在PHP中:
<!-- These have the "class" attribute instead of "id" now -->
<input type="hidden" name="userid" class="userid" value="<?php echo $row11['user_id']; ?>">
<input type="text" value="<?php echo $row11['plot_id']; ?>" name="plotid" class="plotid">
在JS中:
// Get lists of HTML elements for inputs
// (selected by class)
var userIDElements = document.getElementsByClassName('userid');
var plotIDElements = document.getElementsByClassName('plotid');
// Array.from() converts the HTMLCollection to a normal JS Array
// (this is necessary so we can use .map)
// .map(func) runs func on each element of the array, and returns a new
// array with the results of that
// e.g. here, the function takes each <input> element found, and returns
// its value, so now we have a list of values rather than a list of elements
var userIDs = Array.from(userIDElements).map(function (element) { return element.value; });
var plotIDs = Array.from(plotIDElements).map(function (element) { return element.value; });
有关.map()
的更多详细信息,请参见here。
编辑:我之前输入的代码有误-抱歉。