请在下面检查我的代码:
PHP&HTML代码(file1.php):
<?php
$conn = //connected to db successfully.
$sql = "SELECT t1.column1 AS Column_1 FROM table1 t1";
$rs = mysqli_query($conn,$sql);
$rows= mysqli_fetch_assoc($rs);
do{
?>
<button data-id="<?php echo $rows['Column_1']; ?>" type="button" onclick="handle_item('id')">Click Me</button> <br>
<?php }while($rows = mysqli_fetch_assoc($rs)); ?>
jQuery AJAX代码(file1.php):
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data: {
'button_id': c
},
success: function (data) {
alert(data);
}
});
}
</script>
PHP代码(handle_input.PHP):
<?php
echo "Button with id ".$_POST['item_id]." clicked!";
?>
现在的问题是(正如您所料)本例中臭名昭著的错误"undefined index:button_id"错误。当我点击其中一个按钮时,我会收到一个警告错误。我已经读过SO上的重复问题,但不幸的是,我读到的问题都无法解决我的问题。我很感激你的指导。
此外,正如您从我的代码中看到的,我从数据库中获取了几个按钮,在显示时,我为每个按钮分配了一个数据id,并在ajax中使用该数据id在"handle_input.php"中使用,我想接收我点击的每个按钮id。提前感谢。
更新:
我已经有一段时间没有问这个问题了,但我一直对我的问题感到好奇:为什么数组模式(data:{"button_id":c})在$.ajax函数中不适用(这会导致$_POST变量出现未定义的索引错误),而字符串模式(data:"usg_id="+c)适用?
您正在发送:
button_id:..
但您正在使用,也缺少'
$_POST['item_id]
更改为:
$_POST["button_id"]
更新
添加this
作为第一个参数:
onclick="handle_item(this, 'id')"
然后,将handle_item
功能更改为:
function handle_item(obj,item_id) {
var c = $(obj).data(item_id);
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data:"item_id="+c,
success: function (data) {
alert(data);
}
});
}
</script>
函数中没有定义button_id,因此出现错误。同样在handle_input中,您正在获取item_id