假设我有一些来自数据库的数据并存储在一个数组中,如下所示:
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
,我可以将数组的内容打印为html表,如下所示:
Id name status
0 name1 status1
1 name2 status2
我想在每行末尾使用'status'下拉列表来更改每个条目的状态,并更新到数据库表中。我的问题是:当我选择下拉列表中的一个选项时,我如何获得每行的行id("id"列)?如何将这些信息传递到后端以更新数据库表?我想它应该使用一些javascript。下面是代码:
<?php
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
?>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Id</td>
<td>name</td>
<td>status</td>
</tr>
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
echo '<select>';
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
</body>
</html>
谢谢你的帮助!
你可以:
-
给每个select的id对应于数据行
-
On change(jQuery),获取选择的值,并使用jQuery ajax调用发送rowID,和'StatusValue'到处理页面
-
显示数据返回时的状态信息
—构建Select
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
**echo '<select id="' + $testArray[$i][0] + '">';**
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
—jQuery(您将需要jQuery文件,从jquery.com下载)
$(document).ready(function(){
$('select').change(function () {
var rowIdVal = $(this).attr('id'); // the id of the select (your rowID)
var statusVal = $(this).val(); // the value of the select
// post id to the server using ajax (you can use jQuery ajax request)
////I would check if the values are valid and not null...
$.ajax({
type: "POST",
url: "YOURHANDLERFILE.php",
data: {status: statusVal, rowId: rowIdVal},
success: function(d){
//show a status message
}
});
});
});
您可以:
- 将行id存储在第一列的隐藏字段中,并使用jQuery获取
- 存储为
id
属性,然后使用jQuery获取值 -
(我认为最好的一个)存储在
id
属性的id在您的select
控制,然后获得值选择索引更改使用jQuery在HTML中有:
在javascript:<select id="1">
$('select').change(function () { var id = $(this).attr('id'); // post id to the server using ajax (you can use jQuery ajax request) });
我会这样做
$('#yourTableId').find('select').change(function() { //bind a change event to the selects
$(this).closest('tr') //this way you get the tr element of the row you changed the select value
.find('td:first') //or .find('td').first(). This will give you the td element for the Id column
.val(); //The actual value of the td Id element
});