嗯,我的问题是我试图插入,更新和删除通过使用Ajax的表单发送数据,但我努力提交按钮,因为我需要每个人执行一个每次我点击它们的具体动作调用url的地方在哪里的PHP说明,但正如你可以在Ajax中看到的动作只执行提交,而不是取决于我点击的按钮,我真的需要解决这个...使用Ajax的每个按钮的不同动作
FORM
<form method="post" id="form_shirt" enctype="multipart/form-data">
ID:<br>
<input type="hidden" name="id_shirt" id="id_shirt" class="form-control" >
Name:<br>
<input type="text" name="name_shirt" id="name_shirt" class="form-control" required="required">
Price:<br>
<input type="text" name="price_shirt" id="price_shirt" class="form-control" required="required">
<input type="submit" name="btninsert" id="btninsert" value="Insert" class="btn btn-success"/>
<input type="submit" name="btnupdate" id="btnupdate" value="Update" class="btn btn-warning">
<input type="submit" name="btndelete" id="btndelete" value="Delete" class="btn btn-danger">
</form>
AJAX
$(document).ready(function(event){
$('#form_shirts').on("submit", function(event){
event.preventDefault();
$.ajax({
url:"insert_shirts.php",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data){
$('#form_shirt')[0].reset();
$('#table_shirt').html(data);
}
});
});
$('#form_shirts').on("submit", function(event){
event.preventDefault();
$.ajax({
url:"update_shirts.php",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data){
$('#form_shirt')[0].reset();
$('#table_shirt').html(data);
}
});
});
$('#form_shirts').on("submit", function(event){
event.preventDefault();
$.ajax({
url:"delete_shirts.php",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data){
$('#form_shirt')[0].reset();
$('#table_shirt').html(data);
}
});
});
});
PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "shirts");
$output = '';
$name_shirt = mysqli_real_escape_string($connect, $_POST["name_shirt"]);
$price_shirt = mysqli_real_escape_string($connect, $_POST["price_shirt"]);
$query = "INSERT into shirts (name, price)
VALUES ('$name_shirt','$price_shirt') ";
if(mysqli_query($connect, $query))
{
$output .= '<label class="text-success">Data Inserted</label>';
$select_query = "SELECT id_shirt, name, price FROM shirts";
$result = mysqli_query($connect, $select_query);
$output .= '
<table id="shirts" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<tbody>
<td>' . $row["id_shirt"] . '</td>
<td>' . $row["name"] . '</td>
<td>' . $row["price"] . '</td>
</tr>
</tbody>
';
}
$output .= '</table>';
}
echo $output;
?>
你不需要为每个按钮点击写好。准备1个document.ready,然后将3个按钮点击到它自己的函数中,然后在.ready中调用函数,你的submit是表单吗?将其更改为按钮,点击使其与按钮点击完全相同 – Se0ng11
那么,为什么不给这些按钮一个类名称,为该类的所有按钮设置click事件,并使用ID设置PHP文件的名称或者使用'data-'属性?这样,你有一个函数可以用于所有的三个按钮,而不是创建3个函数,除了将数据发送到不同的文件名外,它们完全相同...... – NewToJS
你不能有三个''按钮。只需将它们定义为普通'