嗯,我的問題是我試圖插入,更新和刪除通過使用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
你不能有三個''按鈕。只需將它們定義爲普通'